I came up with a pretty good recursive solution, which takes into account quite a few possibilities (having "\n" or " " in the string, and if a word is simply too long, it splits the word):
function convertTextToMultiline(dc, text){
var extraRoom = 0.8;
var oneCharWidth = dc.getTextWidthInPixels("EtaoiNshrd",Graphics.FONT_SMALL)/10;
var charPerLine = extraRoom * dc.getWidth()/oneCharWidth;
return convertTextToMultilineHelper(text, charPerLine);
}
function convertTextToMultilineHelper(text, charPerLine) {
if (text.length() <= charPerLine) {
return text;
} else {
var i = charPerLine + 1;
for (; i >= 0; i--) {
if (text.substring(i, i + 1).equals("\n")) {
break;
}
}
if (i >= 0) {
var line = text.substring(0, i);
var textLeft = text.substring(i + 1, text.length());
var otherLines = convertTextToMultilineHelper(textLeft, charPerLine);
return line + "\n" + otherLines;
} else {
var lastChar = charPerLine + 1;
while (!(text.substring(lastChar, lastChar + 1).equals(" ") || text.substring(lastChar, lastChar + 1).equals("\n"))&& lastChar >= charPerLine/2) {
lastChar--;
}
if (lastChar >= charPerLine/2) {
var line = text.substring(0, lastChar + 1);
var textLeft = text.substring(lastChar + 1, text.length());
var otherLines = convertTextToMultilineHelper(textLeft, charPerLine);
return line + "\n" + otherLines;
} else {
var line = text.substring(0, charPerLine) + "-";
var textLeft = text.substring(charPerLine, text.length());
var otherLines = convertTextToMultilineHelper(textLeft, charPerLine);
return line + "\n" + otherLines;
}
}
}
}
It might not be the prettiest or the most efficient solution, but it sure works!