String str = "Hello";
canvas.drawText(str,x,y,paint);
//1.粗略计算文字宽度
paint.measureText(str);
//2.计算文字所在矩形,可以得到宽高
Rect rect = new Rect();
paint.getTextBounds(str,0,str.length(),rect);
int w = rect.width();
int h = rect.height();
//3.精确计算文字宽度
int textWidth = getTextWidth(paint,str);
public static int getTextWidth(Paint paint,String str){
int iRet = 0;
if(str != null && str.length() > 0){
int len = str.length();
float[] widths = new float[len];
paint.getTextWidths(str,widths);
for(int j = 0; j < len;j++){
iRet += (int)Math.ceil(widths[j]);
}
}
return iRet;
}
Android drawText获取text宽度的三种方式 .
最新推荐文章于 2023-08-29 18:22:43 发布