How can I get the height and width values of View's text size in pixels?

893 Views Asked by At

I need to get height and width of the textView's text. Yes there is a method called textView.getTextSize(), but I don't understand what that size means: a height, a width or something else? I need the exact width and height values (it will be good, if values will be in pixels not sp).

3

There are 3 best solutions below

2
Kalai On BEST ANSWER

One approach could be with the use of getPaint() and getTextBound()

String text = (String) textView.getText();
Rect textBound = new Rect();
textView.getPaint().getTextBounds(text,0,text.length(),textBound);
int textHeight = textBound.height();
int textWidth = textBound.width();

I am not entirely sure of the height and width being in pixel. Based on this Q&A in regards to RectF, I believe Rect as well should use pixels.

1
npace On

getTextSize() returns the TextView's line height in pixels.

I think what you're looking for is textView.getLayout().getHeight() and textView.getLayout().getWidth(), although the Layout can be null if the TextView changed recently.

0
JoxTraex On

getTextSize() returns the size of the text set on the which is effectively the font size of the TextView, you can determine this by looking at the setTextSize method: https://developer.android.com/reference/android/widget/TextView#setTextSize(int,%20float)

To figure out the height/width of a TextView you could use:

https://developer.android.com/reference/android/view/View#getMeasuredHeight() https://developer.android.com/reference/android/view/View#getMeasuredWidth()

This is assuming that the view has been measured and laid out.

As for useful conversions that could be helpful here refer to: How to convert DP, PX, SP among each other, especially DP and SP?

Whenever unsure about what a method does, check the docs and also check other methods to figure out what it does, like you can figure out what getTextSize returns by looking at setTextSize.