How to get the right font size drawing the text?


what I want is to get the right font size that fit the height in [11,12,16]

when height = 11 and I want to get the right font size of the text. and I use that font size will get the max height 11 of the text.

fontSize=30;
while(true)
{
bitmap = Bitmap.createBitmap(306, 90, Bitmap.Config.Argb8888);
canvas.drawColor(Color.ParseColor("#000000"))
_paint.setTextSize(fontSize);

...get the height
if(height==11){
return fontSize;
}

fontSize--;
}

first I will set the fontSize=30 and then get height of the text using pixel.and then fontSize--;

then I will the the fontSize that height =11;

but actually I get the wrong font Size.

what I get is [16, 17, 24] and it is wrong.

I set the fontSize = 16 then draw Text the height is not 11.

-1
Nov 18 at 1:09 PM
User AvatarAngella Yu
#android

Accepted Answer

setTextSize(16) makes the em-square (include ascent/descent padding), not an drawn glyph pixel height, therefore 11px tall letter with sizes 16 are normal.

if the drawn height doesnt match the 11, check the exact string you're nnow drawing (getTextBounds depends on whether the string have capitals/descenders, anti-aliasing adds 1-2px). stop calling Bitmap.createBitmap inside a while(true), just measure with Rect instead:

jave code for the noob

Rect r = new Rect();
for (float sz = 30f; sz > 1f; sz -= 0.5f) {
    _paint.setTextSize(sz);
    _paint.getTextBounds(text, 0, text.length(), r);
    if (r.height() <= 11) return sz;
}
User Avataruser1720359
Nov 18 at 1:32 PM
0