如何计算字体的宽度?

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

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

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); 

请参见Graphics.getFontMetrics()和FontMetrics.stringWidth() 。

这是一个简单的应用程序,可以向您展示在测试String的宽度时如何使用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); } } 

看看这个精彩的演示文稿,特别是“文本测量”部分。 它解释了可用的大小及其用途: 桌面应用程序的高级Java 2D™主题 。

Java2D FAQ中的更多信息:逻辑,视觉和像素界限之间有什么区别?

使用以下类中的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(); } } 

您可以从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();