在 J2ME 中测量属性字符串的宽度



我正在针对J2ME中的Java Personal Basis Profile编写代码。我需要以像素为单位测量属性字符串的宽度。

在Java SE中,我会从AttributedString中获取一个AttributedCharacterIterator并将其传递给FontMetrics#getStringBounds,但是在J2ME PBP中,FontMetrics没有getStringBounds方法或任何其他接受CharacterIterator的方法。

我该怎么办?

我为此非常努力。我需要将面板大小调整为属性字符串的宽度。我的解决方案是:

double GetWidthOfAttributedString(Graphics2D graphics2D, AttributedString attributedString) {
    AttributedCharacterIterator characterIterator = attributedString.getIterator();
    FontRenderContext fontRenderContext = graphics2D.getFontRenderContext();
    LineBreakMeasurer lbm = new LineBreakMeasurer(characterIterator, fontRenderContext);
    TextLayout textLayout = lbm.nextLayout(Integer.MAX_VALUE);
    return textLayout.getBounds().getWidth();
}

它使用 LineBreakMeasurer 查找字符串的 TextLayout,然后简单地检查 TextLayout 的 with。(换行宽度设置为 Integer.MAX_VALUE,因此宽度超过该宽度的文本将被截断)。

您可以找到文本的宽度(以像素为单位)。

String text = "Hello world";
int widthOfText = fontObject.charsWidth(text.toCharArray(), 0, text.length());

现在,您将在可变宽度文本中拥有以像素为单位的文本宽度;

最新更新