绘制成圆圈的字符串

时间:2014-01-21 19:33:44

标签: java string java-2d fontmetrics

我知道Java的drawString(String str, int x, int y)方法;但是,有时候我想要的是在给定字体大小的情况下(在pts中或根据圆圈的大小)在其中间标记一个带有适当字符串的圆圈。有没有一种简单的方法可以做到,或者是否必须自己进行数学计算?如果是这样,如何根据字体大小(int pts)计算字符串的宽度?

1 个答案:

答案 0 :(得分:0)

这是一个例子。文本绘图是Software Monkey列出的答案的修改版本,使用给定的坐标,而不是在组件的中心绘图。

如果您想要绘制一个未覆盖整个组件的圆圈,则必须计算圆的中心,并将其传递到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.
}

}