Skip to content

Instantly share code, notes, and snippets.

@shnhrrsn
Created March 1, 2012 15:51
Show Gist options
  • Save shnhrrsn/1950643 to your computer and use it in GitHub Desktop.
Save shnhrrsn/1950643 to your computer and use it in GitHub Desktop.
Get the height of a block of text constrained to a max width.
public static int getTextHeight(String text, int maxWidth, float textSize, Typeface typeface) {
TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
paint.setTextSize(textSize);
paint.setTypeface(typeface);
int lineCount = 0;
int index = 0;
int length = text.length();
while(index < length - 1) {
index += paint.breakText(text, index, length, true, maxWidth, null);
lineCount++;
}
Rect bounds = new Rect();
paint.getTextBounds("Py", 0, 2, bounds);
return (int)Math.floor(lineCount * bounds.height());
}
@alexrainman
Copy link

It helped me today too :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment