java - 绘制圆圈内刻的字符串

标签 java string java-2d fontmetrics

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

最佳答案

这是一个例子。文本绘图是 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.
}

关于java - 绘制圆圈内刻的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21267412/

相关文章:

java - 如何拖动多边形?

java - 无法获得正确的字体字符宽度

java - 如何解决第 1 行第 "Incorrect integer value: ' 列的错误 'type_id' null'?

c# - 从字符串中删除所有空格的有效方法?

c# - 拆分字符串时使用十六进制作为分隔符

regex - 在perl中分割包含经度或纬度表达式的字符串

java - 当我安装了 Java 7 时,cassandra 2 提示 Java 7

java - 在构造函数中使用 lambda 时的“this”引用转义

java - 覆盖 Java 泛型方法

java - JPanel 不显示图形