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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With