简体   繁体   中英

How to draw a circle on Canvas?

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));
            }
        }

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);
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM