3

如何找到两个矩形之间的距离?相交的距离应返回 0。

4

3 回答 3

5

这是一个计算由 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);
}
于 2013-02-01T13:56:40.123 回答
3

在一个稍微相关的注释中,这里是如何计算两个给定 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-05-14T12:17:42.267 回答
1

将快速版本添加到批准的答案中:

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)
    }
}
于 2020-06-11T17:10:40.917 回答