gpt4 book ai didi

java - 检查圆是否包含矩形

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:59 25 4
gpt4 key购买 nike

如何检查圆是否完全包含矩形(在 Java 中)?

public class Circle {
//x and y define the top left corner of the square bounding this circle
public int x, y, radius;
}

public class Rectangle {
//x and y define the top left corner
public int x, y, width, height;
}

public boolean circleContainsRectangle(Circle circle, Rectangle rect) {
...
}

最佳答案

以下是 cartesian 的答案轴在哪里 (0, 0)位于左下角。

编辑由于您的 x, y是广场的左上角。将它们转换为居中:

x = x+r
y = y-r

圆的方程是x^2 + y^2 = r^2 , 现在给出点{x, y}当iff x^ + y^2 <= r^2 时将位于圆圈内或圆圈上.现在,我们可以安全地假设如果所有四个角点都在圆内或圆上,则矩形将位于圆内。使用上述假设伪代码来查找矩形是否包含在圆中:

boolean contains(Circle c) {
Point p_rect_1 = {x, y};
Point p_rect_2 = {x + width, y };
Point p_rect_3 = {x + width, y + height };
Point p_rect_4 = {x, y + height };
Point[] points = new Point[] { p_rect_1, p_rect_2, p_rect_3, p_rect_4 };

foreach(Point p : points) {
// ** is raise to power
if ((c.x - p.x)**2 + (c.y - p.y)**2 > c.r**2) {
return false;
}
}
return true;
}

编辑更优化的计算方法(Jim 在下面的评论中建议)是计算矩形离圆心最远的角:

dx = max(centerX - rectLeft, rectRight - centerX); 
dy = max(centerY - rectTop, rectBottom - centerY);
return radius*radius >= dx*dx + dy*dy

关于java - 检查圆是否包含矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097290/

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