2011-09-29 58 views
2

假設我有2個矩形如下之間矢量:得到2個矩形

  1. 一個包圍其他
  2. 它們共享至少2個邊(3或所有4也是可能的)

如何我能得到描述內部矩形移動到非共享邊所需的位移的矢量嗎?

+0

你使用WPF? –

+0

是的,但我計算這個功能不能訪問畫布,我真的只需要偏移/矢量 – mtijn

回答

3

如果我理解正確的話,那麼你應該遵循這些步驟:雙方共享

  1. 查找角落。
  2. 從內部和外部矩形獲取oposit角。
  3. vector = outerRecCorner - innerRecCorner
+0

,這聽起來像我需要的,但它並沒有考慮位移限於水平或垂直平面( 3個共享邊),也沒有非位移(4個共享邊) – mtijn

+0

與3個共享邊它會給你矢量正交於其中一邊。 4邊結果將是[0,0],所以這將是正確的答案。 –

+0

是的,在第1步中,只需找到兩個矩形共用的_any_角。其餘的步驟將會起作用。 –

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; 
    } 
} 

然後找出它的角oposite:

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; 
+0

+1謝謝你這樣詳細的答案!我已經重申了包括'數學'的問題,我一定會使用這個(但是使用linq重構它),再次感謝! – mtijn