Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure the width of an AttributedString in J2ME

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

In Java SE, I'd get an AttributedCharacterIterator from my AttributedString and pass it to FontMetrics#getStringBounds, but in J2ME PBP, FontMetrics doesn't have a getStringBounds method, or any other method that accepts a CharacterIterator.

What do I do?

like image 584
Dan Fabulich Avatar asked May 10 '12 09:05

Dan Fabulich


1 Answers

I struggled really hard with this. I needed to resize a panel to the width of an AttributedString. My solution is:

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();
}

It uses the LineBreakMeasurer to find a TextLayout for the string, and then simply checks the with of the TextLayout. (The wrapping width is set to Integer.MAX_VALUE, so texts wider than that will be cut off).

like image 183
foolo Avatar answered Oct 22 '22 16:10

foolo