如何判斷兩矩形是否相交

【解題思路】
假定矩形是用一對點表達的(minx,miny)(maxx,   maxy)  
那麼兩個矩形rect1{(minx1,miny1)(maxx1,   maxy1)},       rect2{(minx2,miny2)(maxx2,   maxy2)}  
   
相交的結果一定是個矩形,構成這個相交矩形rect{(minx,miny)(maxx, maxy)}的點對座標是:  
  minx   =   max(minx1,   minx2)  
  miny   =   max(miny1,   miny2)  
  maxx   =   min(maxx1,   maxx2)  
  maxy   =   min(maxy1,   maxy2)  
   
  如果兩個矩形不相交,那麼計算得到的點對座標必然滿足  
  minx   >   maxx  
  或者  
  miny   >   maxy  
 
  判定是否相交,以及相交矩形是什麼都可以用這個方法一體計算完成

【源代碼】

  1. bool CardRectManager::IsIntersect(RECT* pRect1, RECT* pRect2)
  2. {
  3.     int nMaxLeft = 0;
  4.     int nMaxTop = 0;
  5.     int nMinRight = 0;
  6.     int nMinBottom = 0;
  7.     
  8.     // Get the max left.
  9.     if (pRect1->left >= pRect2->left)
  10.     {
  11.         nMaxLeft = pRect1->left;
  12.     }
  13.     else
  14.     {
  15.         nMaxLeft = pRect2->left;
  16.     }
  17.     // Get the max top.
  18.     if (pRect1->top >= pRect2->top)
  19.     {
  20.         nMaxTop = pRect1->top;
  21.     }
  22.     else
  23.     {
  24.         nMaxTop = pRect2->top;
  25.     }
  26.     // Get the min right.
  27.     if (pRect1->right <= pRect2->right)
  28.     {
  29.         nMinRight = pRect1->right;
  30.     }
  31.     else
  32.     {
  33.         nMinRight = pRect2->right;
  34.     }
  35.     // Get the min bottom.
  36.     if (pRect1->bottom <= pRect2->bottom)
  37.     {
  38.         nMinBottom = pRect1->bottom;
  39.     }
  40.     else
  41.     {
  42.         nMinBottom = pRect2->bottom;
  43.     }
  44.     // Judge whether intersects.
  45.     if (nMaxLeft > nMinRight || nMaxTop > nMinBottom)
  46.     {
  47.         return false;
  48.     }
  49.     else
  50.     {
  51.         return true;
  52.     }
  53. }
發佈了31 篇原創文章 · 獲贊 5 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章