我有一个WPF应用程序,其中我在画布中绘制矩形。我需要添加一个功能,当我绘制一个矩形时,如果旁边有一个矩形(例如:假设第一个矩形x坐标是236和第二个矩形坐标是235)我需要将第二个矩形x坐标捕捉到236,如图所示。 仅当距离差为10时才会进行捕捉。
我已经编写了以下代码来执行此操作。
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPos = e.GetPosition(Canvas);
System.Windows.Point curPosition = e.GetPosition(SectionCanvas);
rect = new System.Windows.Shapes.Rectangle
{
Stroke = brushColor,
StrokeDashArray = new DoubleCollection { 2, 2 },
Tag = "rectangle"
};
Canvas.SetLeft(rect, startPos.X);
Canvas.SetTop(rect, startPos.X);
SectionCanvas.Children.Add(rect);
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
currentPos = e.GetPosition(SectionCanvas);
var x = Math.Min(currentPos.X, startPos.X);
var y = Math.Min(currentPos.Y, startPos.Y);
var w = Math.Max(currentPos.X, startPos.X) - x;
var h = Math.Max(currentPos.Y, startPos.Y) - y;
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
if(rect == null)
{
MessageBox.Show("Could not capture section, Please try again");
return;
}
endPos = e.GetPosition(SectionCanvas);
IEnumerable<Rect> coordinates = rectCollection.Select(r => new Rect(Canvas.GetLeft(r), Canvas.GetTop(r), r.Width, r.Height));
Rect newCordinates = new Rect(Canvas.GetLeft(rect), Canvas.GetTop(rect), rect.Width, rect.Height);
if (coordinates.Any(c => c.IntersectsWith(newCordinates)))))
{
MessageBox.Show("New Rectangle intersects with existing rectangle");
Canvas.Children.Remove(rect);
return;
}
rectCollection.Add(rect);
rect = null;
foreach(Point p in tempCollection)
{
if((startPos.X <= (p.X + 10) && startPos.X >= (p.X -10)))
{
startPos.X = p.X;
}
if(endPos.X <= (p.X + 10) && endPos.X >= (p.X - 10))
{
var x1 = Math.Max(endPos.X,p.X) - Math.Min(endPos.X, p.X);
var w1 = startPos.X - x1;
endPos.X = p.X;
startPos.X = w1;
}
if ((startPos.Y <= (p.Y + 10) && startPos.Y >= (p.Y - 10)))
{
startPos.Y = p.Y;
}
if (endPos.Y <= (p.Y + 10) && endPos.Y >= (p.Y - 10))
{
var x1 = Math.Max(endPos.Y, p.Y) - Math.Min(endPos.Y, p.Y);
var w1 = startPos.Y - x1;
endPos.Y = p.Y;
}
}
var x = Math.Min(currentPos.X, startPos.X);
var y = Math.Min(currentPos.Y, startPos.Y);
var w = Math.Max(currentPos.X, startPos.X) - x;
var h = Math.Max(currentPos.Y, startPos.Y) - y;
rect.Width = w;
rect.Height = h;
rect.Stroke = Brushes.Coral;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
rect = null;
tempCollection.Add(startPos);
tempCollection.Add(endPos);
}
当我更改端点值时,上面的代码不起作用。在调试时,我可以看到终点值发生变化,但绘制的矩形不会改变。我无法找出我做错了什么。
答案 0 :(得分:0)
我想出了答案,这是我最后的一个愚蠢的错误。
在计算捕捉后的宽度和高度时,我使用的是currentPos,而不是使用endPos。
var x = Math.Min(endPos.X, startPos.X);
var y = Math.Min(endPos.Y, startPos.Y);
var w = Math.Max(endPos.X, startPos.X) - x;
var h = Math.Max(endPos.Y, startPos.Y) - y;