Basically, the algorithm is as follows:
- Set
maxBreak
to the wrap length.
- If string is shorter than max break, return string.
- Set
nextBreak
to maxBreak
and newString
to ""
and lastBreak
to 0
- Check if char at
nextBreak
is a break char (space, new line, etc.)
- If char is not a break char, subtract one from
nextBreak
and repeat step 4
- If char none of the chars are break chars, you must split the string, so do so at wrap length, so set
nextBreak
to wrap length
- Add substring from
lastBreak
-> nextBreak
and a new line char to newString
- Set
lastBreak
= nextBreak
and add wrap length to nextBreak
- Go back to step 4 until
nextBreak
is larger than the original string length.
In fewer words. You want to start at the maximum wrap length and work backwards until you find a break point. When you find it, insert a newline character. Repeat that until you've reached then end of your original string.
Now, in code:
public static String wrapString(String string, int charWrap) {
int lastBreak = 0;
int nextBreak = charWrap;
if (string.length() > charWrap) {
String setString = "";
do {
while (string.charAt(nextBreak) != ' ' && nextBreak > lastBreak) {
nextBreak--;
}
if (nextBreak == lastBreak) {
nextBreak = lastBreak + charWrap;
}
setString += string.substring(lastBreak, nextBreak).trim() + "\n";
lastBreak = nextBreak;
nextBreak += charWrap;
} while (nextBreak < string.length());
setString += string.substring(lastBreak).trim();
return setString;
} else {
return string;
}
}
Where string
is the string you want to break and charWrap
is the maximum number of characters allowed per line.
To find out what charWrap
should be, you'll likely want to find the average width in pixels of your characters, then see how many you can fit in the space you have available.
BitmapFont
s have agetBounds
method: (libgdx.l33tlabs.org/docs/api/com/badlogic/gdx/graphics/g2d/… You could use it to check when a line goes over the wrap width. \$\endgroup\$ – Anko Mar 6 '13 at 16:47