我知道Java的drawString(String str, int x, int y)
方法;但是,有时我想要的只是在给定字体大小(以 pts 为单位或根据圆的大小)的情况下,在圆的中间用适当的字符串标记圆。有没有一种简单的方法可以做到这一点,还是必须自己做数学?如果是这样,作为字体大小(int pts)的函数,如何计算字符串的宽度?
问问题
1870 次
1 回答
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.
}
}
于 2014-02-06T00:29:45.840 回答