【问题标题】:Measure the width of an AttributedString in J2ME在 J2ME 中测量 AttributedString 的宽度
【发布时间】:2012-05-10 09:07:50
【问题描述】:

我正在 J2ME 中针对 Java Personal Basis Profile 编写代码。我需要测量AttributedString 的宽度(以像素为单位)。

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

我该怎么办?

【问题讨论】:

  • 我应该补充一点:我真正需要做的是将 AttributedString 包装成行。使用 LineBreakMeasurer 会容易得多,我在 J2ME PBP 中也没有。 :-(
  • 使用哪个组件来显示用户界面?画布或 LCD UI(表单、警报、列表...)?能否附上一张图片以便更好地理解?

标签: java java-me fontmetrics


【解决方案1】:

我为此付出了很大的努力。我需要将面板的大小调整为 AttributedString 的宽度。我的解决方案是:

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,因此宽于该值的文本将被截断。

【讨论】:

    【解决方案2】:

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

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

    现在,您将在变量 widthOfText 中获得以像素为单位的文本宽度;

    【讨论】:

    • 这不会给你一个 AttributedString 的宽度,其中部分字符串是粗体/斜体,这就是我的问题所在。 (粗体/斜体字符通常比正常字符宽。)
    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多