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