Continuing to improve on both Dee's and FrinkTheBrave's answers. I've added a Rect to the method to allow for drawing within particular width area. Will look at modifying it to select an appropriate font size and ensure it fits within the correct height area.
This will let you specify the width of the lines that you want to write which is very useful for breaking up an unformatted string of text into similar length lines and drawing them to a canvas.
private void drawMultilineText(String str, int x, int y, Paint paint, Canvas canvas, int fontSize, Rect drawSpace) {
int lineHeight = 0;
int yoffset = 0;
String[] lines = str.split(" ");
// set height of each line (height of text + 20%)
lineHeight = (int) (calculateHeightFromFontSize(str, fontSize) * 1.2);
// draw each line
String line = "";
for (int i = 0; i < lines.length; ++i) {
if(calculateWidthFromFontSize(line + " " + lines[i], fontSize) <= drawSpace.width()){
line = line + " " + lines[i];
}else{
canvas.drawText(line, x, y + yoffset, paint);
yoffset = yoffset + lineHeight;
line = lines[i];
}
}
canvas.drawText(line, x, y + yoffset, paint);
}
private int calculateWidthFromFontSize(String testString, int currentSize)
{
Rect bounds = new Rect();
Paint paint = new Paint();
paint.setTextSize(currentSize);
paint.getTextBounds(testString, 0, testString.length(), bounds);
return (int) Math.ceil( bounds.width());
}
private int calculateHeightFromFontSize(String testString, int currentSize)
{
Rect bounds = new Rect();
Paint paint = new Paint();
paint.setTextSize(currentSize);
paint.getTextBounds(testString, 0, testString.length(), bounds);
return (int) Math.ceil( bounds.height());
}
This answer includes this excellent code snippet found here in a previous answer by user850688 https://stackoverflow.com/a/11353080/1759409