WPF如何在鼠标事件上绘制圆圈

时间:2017-11-21 07:48:48

标签: c# wpf

我是WPF的新手。

我想在鼠标移动事件上在Canvas上画一个圆圈。我已经编写了逻辑来将它拖到画布上。但是我想在鼠标点击我的画布时创建一个圆圈,它应该根据鼠标在画布上移动来调整大小。

我该如何做到这一点?

这是我的代码

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

0 个答案:

没有答案