The signature for our method is:
public static Rectangle calcBoundRect(int centerX, int y,
int diameter)
Before we can write the body of the method, we need to design it by determining the algorithm it should use.
The algorithm for determining a bounding rectangle from the center and diameter of a circle is:
You may have noticed that this calculation requires a bit of math. Luckily we can figure it out once, hide the details in the method, and then just call the calcBoundRect() method to do the calculation for us.
Code for the calcBoundRect() Method
/**
* Returns the bounding rectangle of the specified circle.
*/
public Rectangle calcBoundRect(int centerX, int centerY, int diameter)
{
Rectangle r;
int topLeftX, topLeftY;
// 1. Determine the radius of the circle (diameter / 2).
int radius = diameter / 2;
// 2. Calculate the top left x coordinate
topLeftX = centerX - radius;
// 3. Calculate the top left y coordinate.
topLeftY = centerY - radius;
// 4. The answer is a rectangle, which is returned.
r = new Rectangle(topLeftX, topLeftY, diameter, diameter);
return(r);
}