gpt4 book ai didi

geometry - 两个矩形之间的距离

转载 作者:行者123 更新时间:2023-12-02 14:58:06 25 4
gpt4 key购买 nike

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

最佳答案

这里有一个快速函数,用于计算由 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);
}

关于geometry - 两个矩形之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10347085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com