Java 如何计算字体的宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1524855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate the font's width?
提问by MemoryLeak
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?
我正在使用 java 来绘制一些文本,但是我很难计算字符串的宽度。例如: zheng中国... 这个字符串会占用多长时间?
采纳答案by gavinb
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):
如果您有更复杂的文本布局要求,例如在给定宽度内流动一段文本,您可以创建一个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);
回答by Bombe
回答by akf
here is a simple app that can show you how to use FontMetrics when testing the width of a 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);
}
}
回答by Peter ?tibrany
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.
看看这个很棒的演示文稿,尤其是“文本测量”部分。它解释了可用的大小及其用途:高级 Java 2D?桌面应用程序的主题。
Some more information in Java2D FAQ: What is the difference between logical, visual and pixel bounds?
回答by Ed Poor
Use the getWidth method in the following class:
在以下类中使用 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();
}
}
回答by Mergen Wu
You can find it from Font.getStringBounds():
您可以从 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();