2
如何找到兩個矩形之間的距離?相交距離應該返回0。兩個矩形之間的距離
如何找到兩個矩形之間的距離?相交距離應該返回0。兩個矩形之間的距離
下面是用於計算由CGSize表示的兩個CGRects之間距離的快速功能:
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);
}
在一個稍微有關說明,這裏是如何計算中心兩個給定CGRects的之間的距離:
CGFloat CGRectGetDistanceBetweenCenters(CGRect rect1, CGRect rect2)
{
CGPoint center1 = CGPointMake(CGRectGetMidX(rect1), CGRectGetMidY(rect1));
CGPoint center2 = CGPointMake(CGRectGetMidX(rect2), CGRectGetMidY(rect2));
CGFloat horizontalDistance = (center2.x - center1.x);
CGFloat verticalDistance = (center2.y - center1.y);
CGFloat distance = sqrt((horizontalDistance * horizontalDistance) + (verticalDistance * verticalDistance));
return distance;
}
感謝您的回答。但是,假設矩形的大小不一樣,我應該如何考慮尺寸差異? – 2013-03-06 14:47:45
如果我明白你在問什麼,我不舒服,因爲imo。這種方法將找到兩個CGRect之間的最短距離,而不管它們的大小 – jalmaas 2013-03-07 07:55:52