如何计算字体的宽度?

Mem*_*eak 11 java string width

我使用java绘制一些文本,但我很难计算字符串的宽度.例如:zheng中国......这个字符串会占用多长时间?

gav*_*inb 34

对于单个字符串,您可以获取给定绘图字体的度量标准,并使用它来计算字符串大小.例如:

String      message = new String("Hello, StackOverflow!");
Font        defaultFont = new Font("Helvetica", Font.PLAIN, 12);
FontMetrics fontMetrics = new FontMetrics(defaultFont);
//...
int width = fontMetrics.stringWidth(message);
Run Code Online (Sandbox Code Playgroud)

如果您有更复杂的文本布局要求,例如在给定宽度内流动一段文本,则可以创建一个java.awt.font.TextLayout对象,例如此示例(来自文档):

Graphics2D g = ...;
Point2D loc = ...;
Font font = Font.getFont("Helvetica-bold-italic");
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout = new TextLayout("This is a string", font, frc);
layout.draw(g, (float)loc.getX(), (float)loc.getY());

Rectangle2D bounds = layout.getBounds();
bounds.setRect(bounds.getX()+loc.getX(),
              bounds.getY()+loc.getY(),
              bounds.getWidth(),
              bounds.getHeight());
g.draw(bounds);
Run Code Online (Sandbox Code Playgroud)

  • 无法实例化FontMetrics类型. (20认同)
  • 使用:FontMetrics fontMetrics = g.getFontMetrics(); (3认同)