矩形框相关算法

1,判断两矩形区域是否相交

不考虑矩形是斜的情况,但是看别人写的代码都比较复杂,所以不敢肯定百分之百正确,有认为是错误的请留言,多谢!

代码实现(c++)

struct RECT
{
int left;
int top;
int right;
int bottom;
};

//judge whether two rects intersect
bool IsIntersect(RECT &rect1, RECT &rect2)
{
return !(rect1.left > rect2.right || rect2.left > rect1.right || \
rect1.top
> rect2.bottom || rect2.top > rect1.bottom);
}

除上面的算法外,以前还用过一种算法,通过计算两个矩形框的中心点的距离。具体代码就不贴上来了

2,合并两矩形区域

代码实现(c++)

void MergeRect(RECT &dest_rect, RECT &source_rect)
{
dest_rect.top
= dest_rect.top < source_rect.top ? dest_rect.top : source_rect.top;
dest_rect.left
= dest_rect.left < source_rect.left ? dest_rect.left : source_rect.left;
dest_rect.right
= dest_rect.right > source_rect.right ? dest_rect.right : source_rect.right;
dest_rect.bottom
= dest_rect.bottom > source_rect.bottom ? dest_rect.bottom : source_rect.bottom;
}

3,求点到矩形区域的距离

代码实现(c++)

#include <math.h>

struct POINT
{
int x;
int y;
};

int GetDistance(RECT &rect, POINT &point)
{
POINT nearest_point;

if (point.x < rect.left)
nearest_point.x
= rect.left;
else if (point.x > rect.right)
nearest_point.x
= rect.right;
else
nearest_point.x
= point.x;

if (point.y < rect.top)
nearest_point.y
= rect.top;
else if (point.y > rect.bottom)
nearest_point.y
= rect.bottom;
else
nearest_point.y
= point.y

return sqrt((point.x - nearest_point.x)*(point.x - nearest_point.x) + (point.y - nearest_point.y)*(point.y - nearest_point.y));
}
posted @ 2011-05-27 23:32  LittleAnt  阅读(1514)  评论(0编辑  收藏  举报