Created
March 1, 2012 15:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, thanks for this, it helped me today. You can never know who will stumble upon your blog 4 years after writing it. :)