6

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?

Dan Fabulich
  • 37,506
  • 41
  • 139
  • 175
  • I should add: what I really need to do is wrap the AttributedString into lines. That'd be a lot easier with a LineBreakMeasurer, which I also don't have in J2ME PBP. :-( – Dan Fabulich May 10 '12 at 09:10
  • Which the component uses to display user interface? Canvas or LCD UI (Form, Alert, List...)? Could you attach a picture to better understand? – Douglas Frari Jul 20 '12 at 11:38

2 Answers2

3

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

foolo
  • 804
  • 12
  • 22
-1

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;

Kalai Selvan Ravi
  • 2,846
  • 2
  • 16
  • 28
  • That won't give you the width of an AttributedString, where part of the string is bold/italic, which is what my question was about. (Bold/italic characters are often wider than their normal counterparts.) – Dan Fabulich Aug 12 '12 at 05:27