检查圆是否包含矩形

时间:2012-12-31 04:03:08

标签: java geometry

如何检查Circle 完全是否包含Rectangle(使用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) {
   ...
}

4 个答案:

答案 0 :(得分:4)

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

修改 由于您x, y位于正方形的左上角。将它们转换为中心:

x = x+r
y = y-r

圆的方程是x^2 + y^2 = r^2,现在,当iff {x, y}时,点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

答案 1 :(得分:3)

可能最简单的方法是检查矩形的所有四个角是否都小于距离圆心的radius个单位。如果是,那么矩形中的所有点都在圆圈内。您需要检查的四个点是(x,y),(x +宽度,y),(x,y +高度)和(x +宽度,y +高度)。

注意:奇怪的是,圆圈是从右上角定义的,而矩形是从左上角定义的。确保在计算圆心时考虑到这一点。

答案 2 :(得分:0)

斯威夫特4:

func checkCircleContainsRect(circle: Circle, rect: CGRect) -> Bool
    {
        let dx = max(abs(circle.position.x - rect.minX), abs(rect.maxX - circle.position.x))
        let dy = max(abs(circle.position.y - rect.maxY), abs(rect.minY - circle.position.y))
        return (circle.radius * circle.radius) >= (dx * dx) + (dy * dy)
    }

答案 3 :(得分:-1)

我知道我来晚了,但是我想分享我的想法,如果有什么问题。 我只是使用width / 2和height / 2来定义一半的高度和一半的宽度。接下来,我使用毕达哥拉斯定理来计算中心到拐角的距离,然后只是检查其是否大于半径。我知道它的Java,但我不能在其中编写代码,但是我想用C ++编写相同的程序。无论如何,这里是代码:

#include <iostream>
#include <math.h>

using namespace std;

void rectangle_in_circle(float w, float h,float r){
    //sides of square triangle
    float a;
    float b;
    float c;
    //pythagorean theorem
    b = h/2;
    a = w/2;
    c = sqrt(pow(b,2) + pow(a,2));
    //output
    if(c <= r){
        cout << "true" << endl;
    }else{
        cout << "false" << endl;
    }
    }

int main(){ 

    rectangle_in_circle(4,7,5);
    return 0;
}