如果鼠标移动到画布边界之外,如何处理绘制矩形
本文关键字:何处理 处理 绘制 布边界 鼠标 如果 边界 移动 | 更新日期: 2023-09-27 18:11:49
我有一些代码在Canvas
上绘制矩形。这一切都工作得很好,然而,当鼠标离开Canvas
的边界时,矩形的绘制冻结并且什么也没有发生。一些代码
<Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" Background="Transparent" />
private Point startPoint;
private Rectangle rect;
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2
};
Canvas.SetLeft(rect,startPoint.X);
Canvas.SetTop(rect,startPoint.X);
canvas.Children.Add(rect);
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Released || rect == null)
return;
var pos = e.GetPosition(canvas);
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
rect = null;
}
我想要的是继续绘制矩形,即使我走到Canvas
的边界之外,但显然矩形的尺寸被剪切到Canvas
的边界。
实现这一目标的最佳方法是什么?
应该在MouseDown处理程序中捕获鼠标
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
canvas.CaptureMouse();
...
}
并释放MouseUp处理程序
中的捕获private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
...
canvas.ReleaseMouseCapture();
}