【解題思路】
假定矩形是用一對點表達的(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
判定是否相交,以及相交矩形是什麼都可以用這個方法一體計算完成
【源代碼】
- bool CardRectManager::IsIntersect(RECT* pRect1, RECT* pRect2)
- {
- int nMaxLeft = 0;
- int nMaxTop = 0;
- int nMinRight = 0;
- int nMinBottom = 0;
- // Get the max left.
- if (pRect1->left >= pRect2->left)
- {
- nMaxLeft = pRect1->left;
- }
- else
- {
- nMaxLeft = pRect2->left;
- }
- // Get the max top.
- if (pRect1->top >= pRect2->top)
- {
- nMaxTop = pRect1->top;
- }
- else
- {
- nMaxTop = pRect2->top;
- }
- // Get the min right.
- if (pRect1->right <= pRect2->right)
- {
- nMinRight = pRect1->right;
- }
- else
- {
- nMinRight = pRect2->right;
- }
- // Get the min bottom.
- if (pRect1->bottom <= pRect2->bottom)
- {
- nMinBottom = pRect1->bottom;
- }
- else
- {
- nMinBottom = pRect2->bottom;
- }
- // Judge whether intersects.
- if (nMaxLeft > nMinRight || nMaxTop > nMinBottom)
- {
- return false;
- }
- else
- {
- return true;
- }
- }