绘制文本的时候,通常我们需要计算文本的大小来进行布局。而需要精确计算文本大小时候,需要用Paint的api来获取文本的高度大小,通常的做法是:
String text = "xxx"; Paint pain = new Paint(); pain.setAntiAlias(true); float textSize = 24f; pain.setTextSize(textSize); Rect rect = new Rect(); pain.getTextBounds(text, 0, text.length(), rect); int with = rect.width();//文本的宽度 int height = rect.height();//文本的高度。
但是,有时这样计算是不完全精确的。最终方案其实是:
String text = "xxx"; Paint pain = new Paint(); pain.setAntiAlias(true); float textSize = 24f; pain.setTextSize(textSize); Rect rect = new Rect(); pain.getTextBounds(text, 0, text.length(), rect); int with = rect.left+rect.right; int height = (int) textSize;//一个字体的textSize其实就是字体的高度大小
本文介绍了一种使用Paint API精确计算文本尺寸的方法,并给出了具体的代码实现。通过调整Paint对象的属性和利用getTextBounds方法,可以准确地获取文本的宽度和高度。
2665

被折叠的 条评论
为什么被折叠?



