Android 获取字符串在屏幕上的宽度

     可以通过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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值