简体   繁体   English

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

[英]Draw rectangle and update it on every mouse click

Now I want to draw a rectangle on canvas on mouse click Event.现在我想在鼠标单击事件上在画布上绘制一个矩形。 Here is my code:这是我的代码:

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

It works fine everytime I clicked the mouse, but why is the old rectangle still on the canvas when I redraw the new one?每次单击鼠标时它都能正常工作,但是为什么当我重新绘制新矩形时,旧矩形仍在画布上? What I did wrong?我做错了什么?

EDIT Now it's correct, I don't Need Canvas_MouseMove anymore and instead:编辑现在是正确的,我不再需要 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);
    }

You are calling:您正在致电:

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

And then:然后:

canvas1.Children.Add(rect);

Which will add another new Rectangle into your Canvas.Children collection.这会将另一个新的Rectangle添加到您的Canvas.Children集合中。 If you want to remove the old one first, then call this first:如果您想先删除旧的,请先调用:

canvas1.Children.Remove(rect);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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