简体   繁体   中英

The most efficient way to get text width in android?

I need to detect the biggest text size for the text that fits in (width, height). What is the most fast way of getting text size value?

I've tried to iterate text size in for loop and get Paint.getTextBounds() but it takes a lot of time and the whole invocation takes few seconds. The paint typeface is Typeface.MONOSPACE which should help to save time as char width are equal. Is there any dependency between text size and char width to avoid invoking Paint.getTextBounds() ? The task is pretty similar to getting text size for TextView for match_parent width and height, so does anybody know how to do it quickly?

Because you use Typeface.MONOSPACE , you don't have to calculate the text bounds neither for each character nor for each text size.

Let say you have variable paint , which it's text size set 12 for start. You want to fill the area width , height with text. Now

Rect initialBounds = new Rect();
paint.getTextBounds(" ", 0, 1, initialBounds);
float initialTextSize = 12, increase = 2, currentSize = 12;
int charCount = text.length();//the char count we want to print
int maxCharCount = 0;//max count of chars we can print at currentSize.
do{
    currentSize += increase;
    float charWidth = initialBounds.right * currentSize / initialTextSize;
    float charHeight = initialBounds.bottom * currentSize / initialTextSize;
    int charPerLine = width / charWidth;
    int lineCount = height / charHeight;
    maxCharCount = charPerLine * lineCount;
}
while(maxCharCount > charCount);
currentSize -= increase;//this is the size we are looking for.

After that you can just call paint.setTextSize(currentSize); and draw the text.

I didn't test the code, but it should work. You would need some modifications if you want to also be able to decrease the text size below the initial text size if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM