1.计算单个字符宽度与高度。
Paint paint = new Paint();
char[] cs = "c啊1,,tbG".toCharArray();
for (char c : cs) {
Rect r = new Rect();
char[] txt = new char[] { c };
paint.getTextBounds(txt, 0, 1, r);
Log.e("tt", "字符:" + c + "---height:" + (r.bottom - r.top));
Log.e("tt", "字符:" + c + "width:" + (r.right - r.left));
}
打印结果如下:
11-15 19:28:19.790: E/tt(24764): 字符:c---height:7
11-15 19:28:19.790: E/tt(24764): 字符:cwidth:5
11-15 19:28:19.790: E/tt(24764): 字符:啊---height:10
11-15 19:28:19.790: E/tt(24764): 字符:啊width:11
11-15 19:28:19.790: E/tt(24764): 字符:1---height:10
11-15 19:28:19.790: E/tt(24764): 字符:1width:3
11-15 19:28:19.790: E/tt(24764): 字符:,---height:4
11-15 19:28:19.790: E/tt(24764): 字符:,width:3
11-15 19:28:19.800: E/tt(24764): 字符:,---height:4
11-15 19:28:19.800: E/tt(24764): 字符:,width:2
11-15 19:28:19.800: E/tt(24764): 字符:t---height:9
11-15 19:28:19.800: E/tt(24764): 字符:twidth:4
11-15 19:28:19.800: E/tt(24764): 字符:b---height:10
11-15 19:28:19.800: E/tt(24764): 字符:bwidth:5
11-15 19:28:19.800: E/tt(24764): 字符:G---height:9
11-15 19:28:19.800: E/tt(24764): 字符:Gwidth:6
计算高度:
FontMetrics fm = mTextPaint.getFontMetrics();
Log.e("fm.ascent", fm.ascent+"");
Log.e("fm.descent", fm.descent+"");
Log.e("fm.bottom", fm.bottom+"");
Log.e("fm.top", fm.top+"");
float textheight = fm.bottom - fm.top;
2.计算字符串长度
String text = "as我是啦啦啦的小帅哥";
float width = paint.measureText(text);
Log.e("tt", text + "---width:" + width);
打印结果如下:
11-15 19:28:19.800: E/tt(24764): as我是啦啦啦的小帅哥---width:122.0
3.计算最大限制长度是可以放下多少个字符
//breakText:截取字符串,截取字符串最大长度为50,不超过50时,返回截取的字符数量
int measurennums = paint.breakText(text, true, 50, null);
Log.e("tt", text + "---measurennums:" + measurennums);
转载务必注明出处,否则追究相关责任:
http://blog.csdn.net/u014614038/article/details/52824785