如何计算字体的宽度?

发布于 2024-08-06 17:51:47 字数 64 浏览 3 评论 0原文

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

I am using java to draw some text, but it is hard for me to calculate the string's width.
for example:
zheng中国...
How long will this string occupy?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

只涨不跌 2024-08-13 17:51:47

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

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

For a single string, you can obtain the metrics for the given drawing font, and use that to calculate the string size. For example:

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

If you have more complex text layout requirements, such as flowing a paragraph of text within a given width, you can create a java.awt.font.TextLayout object, such as this example (from the docs):

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);
醉殇 2024-08-13 17:51:47

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


}

here is a simple app that can show you how to use FontMetrics when testing the width of a String:

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


}
油焖大侠 2024-08-13 17:51:47

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

Java2D 常见问题解答:逻辑、视觉和逻辑之间有什么区别像素边界?

Take a look at this great presentation, especially "Text Measurement" part. It explains available sizes and their uses: Advanced Java 2D™ topics for Desktop Applications.

Some more information in Java2D FAQ: What is the difference between logical, visual and pixel bounds?

╰沐子 2024-08-13 17:51:47

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

}

Use the getWidth method in the following class:

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

}
み零 2024-08-13 17:51:47

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

You can find it from 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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文