Drawing lines inscribed in a circle.

I know the Java method drawString(String str, int x, int y); however, sometimes all I want is a circle label with the corresponding line in the middle, given the font size (either in glasses or in accordance with the size of the circle). Is there an easy way to do this, or do you need to do the math in private? And if so, how can one calculate the width of a line depending on the font size (int pts)?

+4
source share
1 answer

Here is an example. A text drawing is a modified version of the answer specified in Software Monkey to use coordinate data instead of drawing in the center of the component.

, , drawCenteredText.

Random , .

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.
}

}

0

All Articles