Measure the width of an AttributedString in J2ME

I am writing code against Java Personal Profile Profile in J2ME. I need to measure the width of an AttributedString in pixels.

In Java SE, I got the AttributedCharacterIterator from my AttributedString and passed it to FontMetrics #getStringBounds, but in J2ME PBP, FontMetrics does not have a method getStringBoundsor any other method that accepts CharacterIterator.

What should I do?

+5
source share
2 answers

I fought very hard with this. I needed to resize the panel to the width of the AttributedString. My decision:

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. ( ​​ Integer.MAX_VALUE, , ).

+2

.

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

widthOfText;

0

All Articles