且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android下如何计算要显示的字符串所占的宽度和高度

更新时间:2022-09-21 18:44:16

查询了google发现在android一下有几种方法可以做到,但是经过实际测试发现下面这种方法是最准确的

Android下如何计算要显示的字符串所占的宽度和高度
Rect bounds = new Rect();
String text = "Hello World";
TextPaint paint;

paint = findViewById(R.id.hello_world).getPaint();
paint.getTextBounds(text, 0, text.length(), bounds);
int width = bounds.width();
Android下如何计算要显示的字符串所占的宽度和高度

 

Paint pFont = new Paint();
Rect rect = new Rect();
pFont.getTextBounds("豆", 0, 1, rect);
Log.v(TAG, "height:"+rect.height()+"width:"+rect.width());

 


本文转自java豆子博客园博客,原文链接:http://www.cnblogs.com/error404/archive/2013/01/25/2876888.html,如需转载请自行联系原作者