View Single Post
Old 12-08-2008, 12:38 PM   #3 (permalink)
Mark Rejhon
Retired BBF Moderator
Mark Rejhon's Avatar
Join Date: Aug 2004
Location: Ottawa, Ontario, Canada
Model: Bold
Carrier: Rogers
Posts: 4,870
Post Thanks: 1
Thanked 0 Times in 0 Posts

Originally Posted by Massif View Post
I'm trying to implement word wrap functionality using Graphics.drawText. Is there any way to measure the width (in pixels) of a string using a particular font? Or will I have to measure each character's width and calculate it that way?
The last poster is correct. The getFont().getAdvance() is the way to determine whether your string needs to wordwrap. Usually by adding 1 character at a time to a line buffer, until it no longer fits. Then you split the string away from the rest of the string, up to the last space (for complete word). Then repeat this task with the remaining text (after the split point), as many times as needed, to do subsequent lines of text...

In the case of wrapping huge numbers of lines (i.e. split a single string into hundreds of lines of text), that can get pretty slow. Large blocks of text (especially tens of thousands of characters) can be a performance bottleneck when doing wordwrapping. Some known optimization techiques: Yes, measure each character's width and put it into a lookup table based on unicode value. Best done on the fly (first time a specific character is encountered). Total them up until it all fits, this is less expensive performance-wise than making a call to getFont().getAdvance() every single character. Another optimization technique when displaying huge amounts of text, is to use an optimized algorithm (i.e. begin searching for the wrap point beginning approximately close to an estimated wordwrapping point, then going backwards/forwards based on whether that amount of text wordwraps or not. If needed, one could even use a binary search algorithm.) for the wordwrap point in the string, this does raise programming complexity but speeds up wordwrapping for hundreds of lines, on a huge string.

Make sure to include handling for words that are longer than the wordwrap line -- often should simply be trunctated and put to the next line. If the info is non-critical (i.e. popup tooltip and complete text otherwise accessible by a different detailed screen, etc), you can just put an ellipsis at the end of the line...
Mark Rejhon
Author of XMPP extension XEP-0301: - specification - open source

Last edited by Mark Rejhon : 12-08-2008 at 12:40 PM.
Offline   Reply With Quote