Paint类中有一个方法:Paint.getTextBounds()它返回被一些文本占用的 Rect
。但是根据this回答它返回的内容与 TextView 的宽度/高度不同。
问题 1:有没有办法使用 Paint.getTextBounds() 返回的 Rect
获取 TextView 的宽度和高度? ?
请注意,我确实需要准确知道宽度/高度。我很高兴知道 rect
的上限可能有 2-3% 的误差,但它不能更大(并且应该适用于任何不依赖于屏幕分辨率和像素密度的手机)然后TextView 边界
Q2:是否有任何其他快速方法来确定具有指定 textSize 的某些文本的宽度和高度?
我知道,宽度可以由 Paint.measureText() 决定,但这不会返回高度。可以通过使用文本创建新的 StaticLayout
然后调用 StaticLayout.getHeight() 来确定高度,但这太慢了。我需要更快的东西。
所有这一切的背景是制作 AutoFitTextView
,它将通过放大或缩小文本大小自动将文本调整到其边界内,而且它应该很快完成,因为会有很多这样的 AutoFitTextView
动态变化非常快。
最佳答案
找到了一种简单且不慢的方法来确定使用不使用 StaticLayout
的特定 Paint
绘制的文本宽度/高度。
public int getTextWidth(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int width = bounds.left + bounds.width();
return width;
}
public int getTextHeight(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.bottom + bounds.height();
return height;
}
技巧的简短描述:Paint.getTextBounds(String text, int start, int end, Rect bounds)
返回 Rect
不在 开始>(0,0)
。也就是说,要获得将通过调用 Canvas.drawText(String text, float x, float y, Paint paint)
使用相同 设置的文本的实际宽度>Paint
来自 getTextBounds()
的对象,您应该添加 Rect
的左侧位置。
注意这个 bounds.left
- 这是问题的关键。
通过这种方式,您将收到与使用 Canvas.drawText()
时收到的相同宽度的文本。
this 中给出了更详细的解释回答。
关于java - 如何使用Paint.getTextBounds()快速获取TextView的宽高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15386025/