矩形框相关算法

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

转载于:https://www.cnblogs.com/little-ant/archive/2011/05/27/2060373.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值