如何计算字体的宽度?

时间:2009-10-06 10:46:48

标签: java string width

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

6 个答案:

答案 0 :(得分: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);

如果您有更复杂的文本布局要求,例如在给定宽度内流动一段文本,则可以创建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);

答案 1 :(得分:7)

答案 2 :(得分:4)

这是一个简单的应用程序,可以向您展示在测试字符串宽度时如何使用FontMetrics:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class GUITest {
    JFrame frame;
    public static void main(String[] args){
        new GUITest();
    }
    public GUITest() {
        frame = new JFrame("test");
        frame.setSize(300,300);
        addStuffToFrame();
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                frame.setVisible(true);
            }
        });
    }           

    private void addStuffToFrame() {    
        JPanel panel = new JPanel(new GridLayout(3,1));
        final JLabel label = new JLabel();
        final JTextField tf = new JTextField(); 
        JButton b = new JButton("calc sting width");
        b.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                FontMetrics fm = label.getFontMetrics(label.getFont());
                String text = tf.getText();
                int textWidth = fm.stringWidth(text);
                label.setText("text width for \""+text+"\": " +textWidth);
            }
        });
        panel.add(label);
        panel.add(tf);
        panel.add(b);
        frame.setContentPane(panel);
    }


}

答案 3 :(得分:2)

看看这个精彩的演示文稿,特别是“文本测量”部分。它解释了可用的尺寸及其用途:Advanced Java 2D™ topics for Desktop Applications

Java2D FAQ: What is the difference between logical, visual and pixel bounds?

中的更多信息

答案 4 :(得分:0)

使用以下类中的getWidth方法:

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;

class StringMetrics {

  Font font;
  FontRenderContext context;

  public StringMetrics(Graphics2D g2) {

    font = g2.getFont();
    context = g2.getFontRenderContext();
  }

  Rectangle2D getBounds(String message) {

    return font.getStringBounds(message, context);
  }

  double getWidth(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getWidth();
  }

  double getHeight(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getHeight();
  }

}

答案 5 :(得分:0)

您可以从Font.getStringBounds()找到它:

String string = "Hello World";
// Passing or initializing an instance of Font.
Font font = ...;
int width = (int) font.getStringBounds(string, new FontRenderContext(font.getTransform(), false, false)).getBounds().getWidth();