【发布时间】:2021-03-15 18:07:31
【问题描述】:
我需要获取 textView 文本的高度和宽度。 是的,有一个名为 textView.getTextSize() 的方法,但我不明白这个大小是什么意思:高度、宽度还是其他什么?我需要准确的宽度和高度值(如果值以像素为单位而不是 sp),那就太好了。
【问题讨论】:
标签: java android text view text-size
我需要获取 textView 文本的高度和宽度。 是的,有一个名为 textView.getTextSize() 的方法,但我不明白这个大小是什么意思:高度、宽度还是其他什么?我需要准确的宽度和高度值(如果值以像素为单位而不是 sp),那就太好了。
【问题讨论】:
标签: java android text view text-size
getTextSize() 返回文本集的大小,这实际上是TextView 的字体大小,您可以通过查看setTextSize 方法来确定这一点:
https://developer.android.com/reference/android/widget/TextView#setTextSize(int,%20float)
要计算出您可以使用的 TextView 的高度/宽度:
https://developer.android.com/reference/android/view/View#getMeasuredHeight() https://developer.android.com/reference/android/view/View#getMeasuredWidth()
这是假设视图已经被测量和布局。
关于此处可能有用的有用转换,请参阅: How to convert DP, PX, SP among each other, especially DP and SP?
当不确定某个方法的作用时,请查看文档并查看其他方法以了解它的作用,就像您可以通过查看 setTextSize 来了解 getTextSize 返回的内容一样。
【讨论】:
一种方法是使用getPaint() 和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();
我不完全确定高度和宽度是否以像素为单位。基于这个Q&A 关于RectF,我相信Rect 也应该使用像素。
【讨论】:
measureText()和getTextBound()宽度的区别,如answer所示。
getTextSize() 返回TextView 的行高(以像素为单位)。
我认为您正在寻找的是 textView.getLayout().getHeight() 和 textView.getLayout().getWidth(),尽管如果 TextView 最近发生更改,Layout 可能为空。
【讨论】: