Reputation: 67
I'm a newbie in WPF and doing MyPaint application. When I draw a circle or a square in my canvas, they follow my mouse when I move it along the Oy pivot. I have no idea to solve this problem. Here are . Thanks for reading.
Point p1, p2;
Point currClick;
//int i = 0;
//private bool flag = true;
Rectangle Myline;
SolidColorBrush scb = new SolidColorBrush(Colors.Black);
private void MyCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
p1 = e.GetPosition(MyCanvas);
Myline = new Rectangle();
Myline.Stroke = scb;
Myline.StrokeThickness = 1;
DoubleCollection Mydash = new DoubleCollection { 5, 3 };
Myline.StrokeDashArray = Mydash;
Canvas.SetLeft(Myline, p1.X);
Canvas.SetTop(Myline, p1.Y);
//Myline.Fill = scb;
MyCanvas.Children.Add(Myline);
}
private void MyCanvas_MouseMove_1(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released)
{
return;
}
else
{
Myline.Width = Math.Max(p2.X, p1.X) - Math.Min(p2.X, p1.X);
Myline.Height = Myline.Width;
Canvas.SetLeft(Myline, Math.Min(p1.X, p2.X));
Canvas.SetTop(Myline, Math.Min(p1.Y, p2.Y));
}
}
Upvotes: 0
Views: 1399
Reputation: 132
Change mouse move-event like this:
private void MyCanvas_MouseMove_1(object sender, System.Windows.Input.MouseEventArgs e)
{
p2 = e.GetPosition(MyCanvas);
if (e.LeftButton == MouseButtonState.Pressed)
{
if (p1.X < p2.X)
Canvas.SetLeft(Myline, p1.X); else Canvas.SetLeft(Myline, p2.X);
if (p1.Y < p2.Y)
Canvas.SetTop(Myline, p1.Y); else Canvas.SetTop(Myline, p2.Y);
Myline.Width = Math.Max(p2.X, p1.X) - Math.Min(p2.X, p1.X);
Myline.Height = Math.Max(p2.Y, p1.Y) - Math.Min(p2.Y, p1.Y);
}
}
Upvotes: 1