绘制矩形并在每次单击鼠标时更新它

本文关键字:鼠标 单击 更新 绘制 | 更新日期: 2023-09-27 18:34:19

现在我想在鼠标单击事件时在画布上绘制一个矩形。这是我的代码:

    protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e)
    {
    ...
        System.Windows.Point startPoint = e.GetPosition(canvas1);
        rect = new System.Windows.Shapes.Rectangle
        {
            Stroke = System.Windows.Media.Brushes.LightBlue,
            StrokeThickness = 10
        };
        Canvas.SetLeft(rect, startPoint.X);
        Canvas.SetTop(rect, startPoint.Y);
        canvas1.Children.Add(rect);
    }
    private void Canvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        rect = null;
    }

每次单击鼠标时它都可以正常工作,但是为什么当我重新绘制新矩形时旧矩形仍在画布上?我做错了什么?

编辑 现在是正确的,我不再需要Canvas_MouseMove,而是:

    protected void imageIR_MouseClick(object sender, System.Windows.Input.MouseEventArgs e)
    {
    ...
        canvas1.Children.Remove(rect);
        System.Windows.Point startPoint = e.GetPosition(canvas1);
        rect = new System.Windows.Shapes.Rectangle
        {
            Stroke = System.Windows.Media.Brushes.LightBlue,
            StrokeThickness = 10
        };
        Canvas.SetLeft(rect, startPoint.X);
        Canvas.SetTop(rect, startPoint.Y);
        canvas1.Children.Add(rect);
    }

绘制矩形并在每次单击鼠标时更新它

您正在调用:

rect = new System.Windows.Shapes.Rectangle(...);

然后:

canvas1.Children.Add(rect);

这将为您的Canvas.Children收藏添加另一个Rectangle。如果要先删除旧的,请先调用以下命令:

canvas1.Children.Remove(rect);