2014-01-21 43 views
4

我知道Java的drawString(String str, int x, int y)方法;然而,有时候我想要的只是在给定字体大小的情况下(在pts中或根据圆的大小)在中间用适当的字符串标记一个圆。有没有简单的方法来做到这一点,还是必须自己做数学?如果是这样,一个字符串的宽度如何计算,作为字体大小(int pts)的函数?绘制字符串刻在一个圆圈内

+4

有没有真正的捷径。使用[Font Metrics](http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html) –

+2

[Measuring Text](http://docs.oracle.com/javase/tutorial/2d/) text/measuringtext.html)可能是一个开始。 – asgs

+0

我通常使用['GlyphVector'](http://stackoverflow.com/a/6296381/418556),但必须有十几种方法来剥皮这只猫。 –

回答

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

}