Get the text height including the font size and set that height

旧时模样 提交于 2019-11-30 21:20:58
Pratik Sharma

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!