I am new to WPF.
I want to draw a circle on Canvas on a Mouse move event. I have already wrote logic to drag it around the canvas. But I wanted to create a circle when mouse clicks on my canvas and it should resize according to mouse move on canvas.
How can I accomplish this?
Here is my Code
Ellipse elip = new Ellipse();
private double pointx;
private double pointy;
private void canvas_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
canvas.MouseMove -= MouseMove_NotDown;
canvas.MouseMove += canvas_PreviewMouseMove;
canvas.MouseUp += canvas_PreviewMouseUp;
Point location = e.MouseDevice.GetPosition(canvas);
elip = new Ellipse();
elip.Height = 1;
elip.Width = 1;
elip.Stroke = Brushes.Black;
elip.StrokeThickness = 2;
Canvas.SetTop(elip, location.Y + 1);
Canvas.SetLeft(elip, location.X + 1);
pointx = location.X + 1;
pointy = location.Y + 1;
canvas.Children.Add(elip);
}
private void MouseMove_NotDown(object sender, MouseEventArgs e)
{
canvas.Cursor = Cursors.Hand;
}
private void canvas_PreviewMouseMove(object sender, MouseEventArgs e)
{
try
{
Point location = e.MouseDevice.GetPosition(canvas);
double height = location.Y - pointy;
double width = location.X - pointx;
if (height >= 0 && width >= 0)
{
elip.Height = height;
elip.Width = width;
}
else if (height < 0 || width < 0)
{
if (height < 0)
{
elip.Height = height + (-height) + 1;
elip.Width = width;
}
else if (width < 0)
{
elip.Height = height;
elip.Width = width + (-width) + 1;
}
}
}
catch
{
}
}
private void canvas_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
elip.Stroke = Brushes.Black;
elip.StrokeThickness = 2;
canvas.MouseMove -= canvas_PreviewMouseMove;
canvas.MouseMove += MouseMove_NotDown;
canvas.MouseUp += canvas_PreviewMouseUp;
}