计算Java中字符串的显示宽度

计算Java中字符串的显示宽度,java,string-length,Java,String Length,如何在Java中计算字符串的长度(以像素为单位) 最好不用秋千 编辑: 我想使用Java2D中的drawString()来绘制字符串 并使用字长进行换行。如果只想使用AWT,则使用(可选指定字体,对于非默认字体)获取FontMetrics,然后查找指定字符串的宽度 例如,如果有一个名为g的Graphics变量,则应使用: int width = g.getFontMetrics().stringWidth(text); 对于其他工具包,您需要向我们提供更多信息-它始终依赖于工具包。它并不总是依

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

最好不用秋千

编辑: 我想使用Java2D中的drawString()来绘制字符串
并使用字长进行换行。

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

例如,如果有一个名为
g
Graphics
变量,则应使用:

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

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

它并不总是依赖于工具包,也不总是需要使用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());


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

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

}

我个人正在搜索一些东西,让我计算多行字符串区域,这样我就可以确定给定区域是否足够大,可以打印字符串,同时保留特定的字体

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;
}
private static Hashtable hash=new Hashtable();
专用字体;
专用LineBreakMeasurer LineBreakMeasurer;
私有int开始,结束;
公共像素长度检查(字体){
this.font=font;
}
公共布尔tryIfStringFits(字符串文本到度量,维度区域到度量){
AttributedString AttributedString=新的AttributedString(textToMeasure,哈希);
attributedString.addAttribute(TextAttribute.FONT,FONT);
AttributedCharacteristor AttributedCharacteristor=
attributedString.getIterator();
start=attributedCharacteristator.getBeginIndex();
end=attributedCharacteristator.getEndIndex();
lineBreakMeasurer=新的lineBreakMeasurer(attributedCharacterIterator,
新的FontRenderContext(null、false、false));
浮动宽度=(浮动)区域到它的宽度;
浮动高度=0;
lineBreakMeasurer.设置位置(开始);
while(lineBreakMeasurer.getPosition()
// 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;
}
//返回字符串的大小(以PICA为单位),给定的空间为200,“W”为1000。
//看https://p2p.wrox.com/access/32197-calculate-character-widths.html
静态整数大小(字符串s)
{
//以下字符以Arial字体按宽度排序
字符串查找=“.:,;”^`!| jl/\\i-()JfIt[]?{}sr*a\'ce_gFzLxkP+0123456789~qvy$sbduefontbcxy#VRKZN%GUAHD@OQ&wmMW”;
int结果=0;
对于(int i=0;i

有趣,但可能不太实用。

没有Swing?您使用的是什么设备?什么字体?什么大小?什么样式?所有这些都会改变显示宽度。您将如何绘制字符串?使用AWT?或其他工具包?字符串的大小(以像素为单位)取决于稍后绘制像素的绘图API(当然,你使用哪种字体,什么字体大小,如果字体是粗体/斜体,等等。)不知道绘图API和字体属性,字符串没有任何大小。@S.Lott。你有一个字符串。我想把它作为一个非问题来结束。@David Arno:我是n00bz上的一个软件。我将添加[初学者]tag.NET等效的还有TextRenderer类,请看,我不认为以这种方式创建仿射Transform和fontRenderContext会产生良好的行为。我想font.getTransfrom()更符合逻辑。您的示例仍在使用AWT功能。例如,对于SWT font,它将不起作用,这就是为什么”它总是依赖于工具箱“@Olofu Mark-getStringBounds只提供逻辑边界。为了更好,它应该使用getBounds()和LineMetrics对象来检索实际高度,包括上升+下降。如果您提供一个示例用法,可能会更清楚,最初我尝试将其作为一个静态方法使用,正如您那样编写。不推荐!但仍然是最好的方法!为什么他们在没有更好的方法时不推荐方法!!!我就是不明白!@Zich:I'm我不确定你说的哪个方法是不推荐的-据我所知,它们在Java 8文档中都没有被标记为不推荐的…@Zich:这是
Graphics
中的一个方法,不是
FontMetrics
。但是你调用的是
Toolkit.getFontMetrics
,它确实是不推荐的,这不是这个方法所讨论的t、 …在这类事情上,你需要非常小心,尤其是在你开始谈论报告bug之前…@Zich:我猜不出-我会使用非弃用方法,或者使用
Toolkit.getFontMetrics
建议的非弃用方法。