本文介绍了两个矩形之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能找到两个矩形之间的距离?相交距离应该返回0。
How can I find the distance between two rectangles? Intersects should return 0 in distance.
推荐答案
以下是一个用于计算CGSize表示的两个CGRect之间距离的快速函数:
Here's a quick function for calculating distance between two CGRects represented by a CGSize:
CGSize CGSizeDistanceBetweenRects(CGRect rect1, CGRect rect2)
{
if (CGRectIntersectsRect(rect1, rect2))
{
return CGSizeMake(0, 0);
}
CGRect mostLeft = rect1.origin.x < rect2.origin.x ? rect1 : rect2;
CGRect mostRight = rect2.origin.x < rect1.origin.x ? rect1 : rect2;
CGFloat xDifference = mostLeft.origin.x == mostRight.origin.x ? 0 : mostRight.origin.x - (mostLeft.origin.x + mostLeft.size.width);
xDifference = MAX(0, xDifference);
CGRect upper = rect1.origin.y < rect2.origin.y ? rect1 : rect2;
CGRect lower = rect2.origin.y < rect1.origin.y ? rect1 : rect2;
CGFloat yDifference = upper.origin.y == lower.origin.y ? 0 : lower.origin.y - (upper.origin.y + upper.size.height);
yDifference = MAX(0, yDifference);
return CGSizeMake(xDifference, yDifference);
}
这篇关于两个矩形之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!