本文介绍了绘制矩形并在每次鼠标单击时更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我想在画布上绘制一个矩形,鼠标点击事件。这是我的代码:
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?
编辑现在是正确的,我不再需要Canvas_MouseMove,而是:
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);
}
推荐答案
p>
You are calling:
rect = new System.Windows.Shapes.Rectangle(...);
然后:
canvas1.Children.Add(rect);
这将添加另一个新 Rectangle
添加到您的
Canvas.Children
集合中。如果你想先删除旧的,然后调用这个:
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);
这篇关于绘制矩形并在每次鼠标单击时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!