如何找到两个矩形之间的距离?相交应该在距离上返回0。
答案 0 :(得分:4)
这是一个快速函数,用于计算由CGSize表示的两个CGRect之间的距离:
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);
}
答案 1 :(得分:2)
在一个稍微相关的说明中,这里是如何计算两个给定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;
}
答案 2 :(得分:0)
为批准的答案添加快速版本:
extension CGRect {
func distance(from rect: CGRect) -> CGSize {
if intersects(rect) {
return CGSize(width: 0, height: 0)
}
let mostLeft = origin.x < rect.origin.x ? self : rect
let mostRight = rect.origin.x < self.origin.x ? self : rect
var xDifference = mostLeft.origin.x == mostRight.origin.x ? 0 : mostRight.origin.x - (mostLeft.origin.x + mostLeft.size.width)
xDifference = CGFloat(max(0, xDifference))
let upper = self.origin.y < rect.origin.y ? self : rect
let lower = rect.origin.y < self.origin.y ? self : rect
var yDifference = upper.origin.y == lower.origin.y ? 0 : lower.origin.y - (upper.origin.y + upper.size.height)
yDifference = CGFloat(max(0, yDifference))
return CGSize(width: xDifference, height: yDifference)
}
}