103

如何在 Java 中计算字符串的长度(以像素为单位)?

最好不使用 Swing。

编辑:我想在 Java2D 中使用 drawString() 绘制字符串,并使用长度进行自动换行。

4

5 回答 5

158

如果您只想使用 AWT,则使用Graphics.getFontMetrics(可选地指定字体,对于非默认字体)获取 aFontMetrics然后FontMetrics.stringWidth查找指定字符串的宽度。

例如,如果您有一个Graphics名为 的变量g,您将使用:

int width = g.getFontMetrics().stringWidth(text);

对于其他工具包,您需要向我们提供更多信息——它总是依赖于工具包。

于 2008-11-03T12:36:40.507 回答
65

它并不总是需要依赖于工具包,或者并不总是需要使用 FontMetrics 方法,因为它需要首先获取 Web 容器或无头环境中不存在的图形对象。

我已经在 web servlet 中对此进行了测试,它确实计算了文本宽度。

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

将必要的值添加到这些尺寸以创建任何所需的边距。

于 2013-02-12T12:49:02.490 回答
8

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

}
于 2013-08-26T18:41:22.027 回答
2

而现在完全不同的东西。以下假设 arial 字体,并根据字符与宽度的线性插值进行疯狂猜测。

// Returns the size in PICA of the string, given space is 200 and 'W' is 1000.
// see https://p2p.wrox.com/access/32197-calculate-character-widths.html

static int picaSize(String s)
{
    // the following characters are sorted by width in Arial font
    String lookup = " .:,;'^`!|jl/\\i-()JfIt[]?{}sr*a\"ce_gFzLxkP+0123456789<=>~qvy$SbduEphonTBCXY#VRKZN%GUAHD@OQ&wmMW";
    int result = 0;
    for (int i = 0; i < s.length(); ++i)
    {
        int c = lookup.indexOf(s.charAt(i));
        result += (c < 0 ? 60 : c) * 7 + 200;
    }
    return result;
}

有趣,但也许不是很实用。

于 2020-03-11T19:29:10.067 回答
1

我个人正在寻找一些东西来让我计算多行字符串区域,所以我可以确定给定区域是否足够大以打印字符串 - 保留特定字体。

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}
于 2017-05-25T12:10:31.673 回答