6

i have a text called Hello now i need to apply fontsize for this say 12 or 18 now as soon as we apply font to the text the text size increases.

so now i need to get the text height including the font size using paint.

i have tried with paint the following:

String finalVal ="Hello";

Paint paint = new Paint();
paint.setTextSize(18);
paint.setTypeface(Typeface.SANS_SERIF);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);

Rect result = new Rect();
// Measure the text rectangle to get the height
paint.getTextBounds(finalVal, 0, finalVal.length(), result);

But its not working , please help

EDIT

i am trying to set the height of webview dynamically based on the textheight i am getting the text height for single line like "Hello" but if there are two lines in the text "My name is abc and my dads name is xyz and my moms name is 123" now its not getting the proper text height".

dakshbhatt21
  • 3,558
  • 3
  • 31
  • 40
Goofy
  • 6,098
  • 17
  • 90
  • 156

2 Answers2

13

Try this way:

String finalVal ="Hello";

Paint paint = new Paint();
paint.setTextSize(18);
paint.setTypeface(Typeface.SANS_SERIF);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);

Rect result = new Rect();
paint.getTextBounds(finalVal, 0, finalVal.length(), result);

Log.d("WIDTH        :", String.valueOf(result.width()));
Log.d("HEIGHT       :", String.valueOf(result.height()));

Here is the output:

WIDTH        : 40
HEIGHT       : 14

If I set this,

String finalVal ="My name is abc and my dads name is xyz and my moms name is 123";

My Output is :

WIDTH        : 559
HEIGHT       : 18
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Pratik Sharma
  • 13,307
  • 5
  • 27
  • 37
  • thanks you the answer i have done this before and i am also getting the same answer but we to set it based on devices height and width, as you can see that hello word and the multi line height doesent have much difference – Goofy Jan 11 '13 at 11:46
3

You can get the text height from the FontMetrics. It is constant for a particular font and font size, no matter what the current text string is.

Paint.FontMetrics fm = mTextPaint.getFontMetrics();
float textHeight = fm.descent - fm.ascent;
float lineHeight = fm.bottom - fm.top + fm.leading;

See my fuller answer here. I compare getTextBounds with FontMetrics in that answer.

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • Doesn't work when trying to center inside a parent canvas. So, not it. The only value that comes close is `FontMetrics#bottom` – TheRealChx101 Sep 30 '19 at 00:05