Drawing strings inscribed in a circle

2k Views Asked by At

I am aware of Java's drawString(String str, int x, int y) method; however, sometimes all I want is to label a circle with an appropriate string in the middle of it, given a font size (either in pts or in accordance to the circle's size). Is there an easy way to do it, or does one have to make the math on one's own? And if so, how can the width of a string be calculated, as a function of the font size (int pts)?

1

There are 1 best solutions below

0
On

Here's an example. The text drawing is a modified version of the answer listed by Software Monkey, to use given coordinates, instead of drawing in the center of a component.

If you wanted to draw a circle that didn't cover the entire component, you would then have to calculate the center of the circle, and pass it into drawCenteredText.

The business with the Random class is there to demonstrate how this method will work with any font size.

public class LabledCircle {

public static void main(String args[]) {
JFrame frame = new JFrame();

// Create and add our demo JPanel
// I'm using an anonymous inner class here for simplicity, the paintComponent() method could be implemented anywhere
frame.add(new JPanel() {
    public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw a circle filling the entire JPanel
    g.drawOval(0, 0, getWidth(), getHeight());

    Random rad = new Random();// For generating a random font size

    // Draw some text in the middle of the circle
    // The location passed here is the center of where you want the text drawn
    drawCenteredText(g, getWidth() / 2, getHeight() / 2, rad.nextFloat() * 30f, "Hello World!");
    }
});

frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void drawCenteredText(Graphics g, int x, int y, float size, String text) {
// Create a new font with the desired size
Font newFont = g.getFont().deriveFont(size);
g.setFont(newFont);
// Find the size of string s in font f in the current Graphics context g.
FontMetrics fm = g.getFontMetrics();
java.awt.geom.Rectangle2D rect = fm.getStringBounds(text, g);

int textHeight = (int) (rect.getHeight());
int textWidth = (int) (rect.getWidth());

// Find the top left and right corner
int cornerX = x - (textWidth / 2);
int cornerY = y - (textHeight / 2) + fm.getAscent();

g.drawString(text, cornerX, cornerY);  // Draw the string.
}

}