I have a problem using my canvas in WPF. I use a lightly modified version of this code : Draw rectangle when mouse dragged using MVVM in WPF
Here is the code :
Xaml :
<Canvas x:Name="cnvImage" Width="800">
<Image MouseDown="img_MouseDown"
MouseMove="img_MouseMove"
MouseUp="img_MouseUp"
Source="/Images/CapturedImage.png">
</Image>
</Canvas>
C# (code behind) :
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;
}
I want to draw Rectangles but there is a problem : if I simply left-click on the canvas, it draws a little red point that seems to be impossible to delete.
Where does this come from ? How can I get rid of it ?
EDIT : the problem has been solved.