可以通过Android的源生方法获取字符串在屏幕上的宽度。在Android源码Paint类中有一个方法measureText就是用来做这个的。
先看源码的介绍。
/**
* Return the width of the text.
*
* @param text The text to measure. Cannot be null.
* @return The width of the text
*/
public float measureText(String text) {
if (text == null) {
throw new IllegalArgumentException("text cannot be null");
}
if (text.length() == 0) {
return 0f;
}
if (!mHasCompatScaling) {
return (float) Math.ceil(native_measureText(text, mBidiFlags));
}
final float oldSize = getTextSize();
setTextSize(oldSize*mCompatScaling);
float w = native_measureText(text, mBidiFlags);
setTextSize(oldSize);
return (float) Math.ceil(w*mInvCompatScaling);
}
源码中的注释提到返回字符串在屏幕中的宽度。
通过API查到用这么一个集成自Paint的类:TextPaint
源码中介绍
/**
* TextPaint is an extension of Paint that leaves room for some extra
* data used during text measuring and drawing.
*/
可以看到这个类就是专门用来获取字符串的大小的。
new 一个这个类的对象
TextPaint paint = new TextPaint();
paint.setTextSize(textSize);// 设置画笔的大小
float result = paint.measureText(text);
这样就可以得到字体的宽度了。需要注意的是这里得到的单位是px。如果需要sp单位的,还要自己转换。
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
paint.setTextSize(scaledDensity * textSize);
float result paint.measureText(text);
这里就不详细解释px转换成sp了。
总结一下,可以归纳为两个工具类:
public static float getTextWidthPX(Context context, String text, float textSize) {
TextPaint paint = new TextPaint();
paint.setTextSize(textSize);
return paint.measureText(text);
}
public static float getTextWidthSP(Context context, String text, float textSize) {
TextPaint paint = new TextPaint();
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
paint.setTextSize(scaledDensity * textSize);
return paint.measureText(text);
}