Android 测量字符串在屏幕中的宽度以及两个空格的表示

6 篇文章 0 订阅

Android 测量字符串在屏幕中的宽度以及两个空格的表示
1.两个空格

<string name="spaceTwo">&#12288;</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;
    }

> 参考链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值