Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if circle contains rectangle

Tags:

java

geometry

How can I check if a Circle completely contains a Rectangle (in 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) {
   ...
}
like image 368
CodeGuy Avatar asked Oct 31 '25 01:10

CodeGuy


1 Answers

Below is answer for cartesian axis where (0, 0) lies on bottom-left corner.

EDIT Since your x, y are top left corner of square. Transform them to be in center:

x = x+r
y = y-r

Equation of circle is x^2 + y^2 = r^2, now given point {x, y} will lie within or on the circle when iff x^ + y^2 <= r^2. Now, we can safety make an assumption that rectangle will lie within circle if all fours corner points lies within or on the circle. Using above assumption pseudo-code for finding if rectangle is contained in circle:

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;
}

EDIT More optimized approach for calculation (suggested by Jim in comments below) would be by calculating the most farthest corner of rectangle from the center of the circle:

dx = max(centerX - rectLeft, rectRight - centerX); 
dy = max(centerY - rectTop, rectBottom - centerY);
return radius*radius >= dx*dx + dy*dy
like image 60
Shivam Avatar answered Nov 01 '25 15:11

Shivam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!