Draw rectangle and update it on every mouse click

為{幸葍}努か 提交于 2019-12-11 20:24:02

问题


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:

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

回答1:


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. If you want to remove the old one first, then call this first:

canvas1.Children.Remove(rect);


来源:https://stackoverflow.com/questions/19246345/draw-rectangle-and-update-it-on-every-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!