Android 测量字符串在屏幕中的宽度以及两个空格的表示
1.两个空格
<string name="spaceTwo"> </string>
2.获取字符串在屏幕中的宽度
TextView content = findViewById(R.id.text_view);
Rect rect = new Rect();
String info = "Measure Text";
content.getPaint().getTextBounds(info,0,info.length(),rect);
//字符串在屏幕中的长度
int width = rect.width()
/** 2020-7-24 更新**/
以上方法获取字体宽度存在偏差
以下方法可正确获取字体宽度
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;
}
3.封装
/**
* 测量字符串在屏幕中的宽高 rect.width() rect.height()
* @param content
* @param info
* @return
*/
public static Rect measureStringWidthOnScrren(TextView content,String info){
Paint paint = content.getPaint();
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;
}