Measure the width of an AttributedString in J2ME

846 views Asked by At

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?

2

There are 2 answers

1
Kalai Selvan Ravi On

You can find the width of the text in pixels.

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

Now, you will have the width of text in pixels in the variable widthOfText;

0
foolo On

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).