How to draw a circle with given X and Y coordinates as the middle spot of the circle?

нαƒєєz picture нαƒєєz · Oct 15, 2013 · Viewed 194.5k times · Source

I have developed a telecommunication application for locating signal strengths from the towers. I have used java swing and I'm having a problem when drawing the circle around the given point of the mobile signal transmitter tower location. I have already calculated the X, Y coordinates and also the radius value.

Please find the below code which I've used to draw the circle and it is having issues.

JPanel panelBgImg = new JPanel() {
    public void paintComponent(Graphics g) {
        g.drawOval(X, Y, r, r);
    }
}

The issue is, it creates the circle but it didn't take the X and Y coordinates as the center point. It took the X and Y coordinates as the top left point of the circle.

Could anyone please help me to draw the circle by having the given X and Y coordinates as the center point of the circle.

Answer

arynaq picture arynaq · Oct 15, 2013

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