How to draw a circle with given X and Y coordinates as the middle spot of the circle?
The fillOval
fits an oval inside a rectangle, with width=r, height = r
you get a circle.
If you want fillOval(x,y,r,r)
to draw a circle with the center at (x,y) you will have to displace the rectangle by half its width and half its height.
public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
x = x-(r/2);
y = y-(r/2);
g.fillOval(x,y,r,r);
}
This will draw a circle with center at x,y
So we are all doing the same home work?
Strange how the most up-voted answer is wrong. Remember, draw/fillOval take height and width as parameters, not the radius. So to correctly draw and center a circle with user-provided x, y, and radius values you would do something like this:
public static void drawCircle(Graphics g, int x, int y, int radius) {
int diameter = radius * 2;
//shift x and y by the radius of the circle in order to correctly center it
g.fillOval(x - radius, y - radius, diameter, diameter);
}
Replace your draw line with
g.drawOval(X - r, Y - r, r, r)
This should make the top-left of your circle the right place to make the center be (X,Y)
,
at least as long as the point (X - r,Y - r)
has both components in range.