Originally Posted by Massif
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...