假设我有2个矩形如下:
如何获得描述内部矩形向上移动到非共享侧所需位移的向量?
答案 0 :(得分:3)
如果我理解正确,那么你应该遵循以下步骤:
vector = outerRecCorner - innerRecCorner
答案 1 :(得分:2)
这更像是数学而不是编程问题:)
让我们假设您有两个矩形:A(内部)和B(外部)。他们有4个角落:
Point [] GetCorners (Rectangle rect)
{
Point [] corners = new Point[4];
Point corners[0] = new Point(rect.X, rect.Y);
Point corners[1] = new Point(rect.X + rect.Width, rect.Y);
Point corners[2] = new Point(rect.X, rect.Y + rect.Height);
Point corners[3] = new Point(rect.X + rect.Width + rect.Width, rect.Y);
return corners;
}
首先找到第一个共享角落:
Point [] cornersListA = GetCorners(A);
Point [] cornersListB = GetCorners(B);
int sharedCornerIndex = 0;
for (int i=0; i<4; i++)
{
if(cornersListA[i].X==cornersListB[i].X && cornersListA[i].Y==cornersListB[i].Y)
{
sharedCornerIndex = i;
break;
}
}
然后找到它的角落对话:
int oppositeCornerIndex = 0;
if(sharedCornerIndex ==0) oppositeCornerIndex = 3;
if(sharedCornerIndex ==3) oppositeCornerIndex = 0;
if(sharedCornerIndex ==1) oppositeCornerIndex = 2;
if(sharedCornerIndex ==2) oppositeCornerIndex = 1;
最后,获取向量(我没有检查代码的这一部分,但它应该工作):
Vector v = new Vector();
v.X = cornersListB[oppositeCornerIndex].X - cornersListA[oppositeCornerIndex].X;
v.Y = cornersListB[oppositeCornerIndex].Y - cornersListA[oppositeCornerIndex].Y;