我在WPF中使用我的画布时遇到问题。我使用这个代码的轻微修改版本: Draw rectangle when mouse dragged using MVVM in WPF
以下是代码:
Xaml:
<Canvas x:Name="cnvImage" Width="800">
<Image MouseDown="img_MouseDown"
MouseMove="img_MouseMove"
MouseUp="img_MouseUp"
Source="/Images/CapturedImage.png">
</Image>
</Canvas>
C#(代码背后):
private Point startPoint;
private Rectangle rectSelectArea;
private void img_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(cnvImage);
// Remove the drawn rectanglke if any.
// At a time only one rectangle should be there
if (rectSelectArea != null)
cnvImage.Children.Remove(rectSelectArea);
// Initialize the rectangle.
// Set border color, fill and width
rectSelectArea = new Rectangle
{
Stroke = Brushes.Red,
StrokeThickness = 2,
Fill = Brushes.Transparent
};
Canvas.SetLeft(rectSelectArea, startPoint.X);
Canvas.SetTop(rectSelectArea, startPoint.Y);
cnvImage.Children.Add(rectSelectArea);
}
private void img_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released || rectSelectArea == null)
return;
var pos = e.GetPosition(cnvImage);
// Set the position of rectangle
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
// Set the dimension of the rectangle
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
rectSelectArea.Width = w;
rectSelectArea.Height = h;
Canvas.SetLeft(rectSelectArea, x);
Canvas.SetTop(rectSelectArea, y);
}
private void img_MouseUp(object sender, MouseButtonEventArgs e)
{
private void img_MouseUp(object sender, MouseButtonEventArgs e)
{
//EDIT : this condition SOLVES the problem
if (e.GetPosition(cnvImage) == startPoint)
cnvImage.Children.Remove(rectSelectArea);
rectSelectArea = null;
}
我想绘制矩形,但是有一个问题:如果我只是左键单击画布,它会绘制一个似乎无法删除的红点。
这是从哪里来的?我怎么能摆脱它?
编辑:问题已经解决了。答案 0 :(得分:1)
我认为您需要检查img_MouseDown
和img_MouseUp
中的位置,如果这些位置相等,那么您应该删除您创建的矩形。
因为你在你的mousedown中添加了strokethickness为2的矩形,你总是会在代码中得到一个矩形,其实际宽度和高度至少为2。