检查圆是否包含矩形

Cod*_*Guy 3 java geometry

如何检查Circle是否完全包含矩形(在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) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

Shi*_*vam 6

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

编辑 由于您x, y是正方形的左上角。转换它们为中心:

x = x+r
y = y-r
Run Code Online (Sandbox Code Playgroud)

圆的等式为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;
}
Run Code Online (Sandbox Code Playgroud)

编辑 更优化的计算方法(由吉姆在下面的评论中建议)是通过计算距圆心最远的矩形角:

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