我在一个封闭的Rect B中有一个Rect A.封闭的Rect B是允许移动Rect A的区域。当试图将Rect A移动到包围Rect B的边界之外时,它应该卡在包围Rect B的边界或角落,并且不再移动。在移动时我手头有以下参数:包围Rect B的属性,移动前Rect A的属性,移动后Rect A的潜在topleft位置。请注意,移动不一定是每像素,也可能在任何方向上(例如)20像素。请告诉我如何有效地做到这一点,但不要过于复杂?
PS:这些只是在WPF画布上绘制的几何图形,因此也允许使用变换,但我在此特定位只有Rect变量,而不是RectangleGeometries。
答案 0 :(得分:0)
最终我创建了一个封闭的A和B矩形,然后在this question中应用了解决方案,如下所示:
private static Point CorrectForAllowedArea(Point previousLocation, Point newLocation, Rect allowedArea, Rect newBox)
{
// get area that encloses both rectangles
Rect enclosingRect = Rect.Union(allowedArea, newBox);
// get corners of outer rectangle, index matters for getting opposite corner
var outsideCorners = new[] { enclosingRect.TopLeft, enclosingRect.TopRight, enclosingRect.BottomRight, enclosingRect.BottomLeft }.ToList();
// get corners of inner rectangle
var insideCorners = new[] { allowedArea.TopLeft, allowedArea.TopRight, allowedArea.BottomRight, allowedArea.BottomLeft }.ToList();
// get the first found corner that both rectangles share
Point sharedCorner = outsideCorners.First((corner) => insideCorners.Contains(corner));
// find the index of the opposite corner
int oppositeCornerIndex = (outsideCorners.IndexOf(sharedCorner) + 2) % 4;
// calculate the displacement of the inside and outside opposite corner, this is the displacement outside the allowed area
Vector rectDisplacement = outsideCorners[oppositeCornerIndex] - insideCorners[oppositeCornerIndex];
// subtract that displacement from the total displacement that moved the shape outside the allowed area to get the displacement inside the allowed area
Vector allowedDisplacement = (newLocation - previousLocation) - rectDisplacement;
// use that displacement on the display location of the shape
return previousLocation + allowedDisplacement;
// move or resize the shape inside the allowed area, right upto the border, using the new returned location
}