gpt4 book ai didi

java - 在 J2ME 中测量 AttributedString 的宽度

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:35 26 4
gpt4 key购买 nike

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

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

我该怎么办?

最佳答案

我为此非常努力。我需要将面板的大小调整为 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,因此宽度大于该值的文本将被截断)。

关于java - 在 J2ME 中测量 AttributedString 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10530795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com