Android 计算字符宽度与高度

1.计算单个字符宽度与高度。

Paint paint = new Paint();
        char[] cs = "c啊1,,tbG".toCharArray();
        for (char c : cs) {
            Rect r = new Rect();
            char[] txt = new char[] { c };
            paint.getTextBounds(txt, 0, 1, r);

    Log.e("tt", "字符:" + c + "---height:" + (r.bottom - r.top));
    Log.e("tt", "字符:" + c + "width:" + (r.right - r.left));

        }

打印结果如下:

11-15 19:28:19.790: E/tt(24764): 字符:c---height:7
11-15 19:28:19.790: E/tt(24764): 字符:cwidth:5
11-15 19:28:19.790: E/tt(24764): 字符:啊---height:10
11-15 19:28:19.790: E/tt(24764): 字符:width:11
11-15 19:28:19.790: E/tt(24764): 字符:1---height:10
11-15 19:28:19.790: E/tt(24764): 字符:1width:3
11-15 19:28:19.790: E/tt(24764): 字符:,---height:4
11-15 19:28:19.790: E/tt(24764): 字符:width:3
11-15 19:28:19.800: E/tt(24764): 字符:,---height:4
11-15 19:28:19.800: E/tt(24764): 字符:,width:2
11-15 19:28:19.800: E/tt(24764): 字符:t---height:9
11-15 19:28:19.800: E/tt(24764): 字符:twidth:4
11-15 19:28:19.800: E/tt(24764): 字符:b---height:10
11-15 19:28:19.800: E/tt(24764): 字符:bwidth:5
11-15 19:28:19.800: E/tt(24764): 字符:G---height:9
11-15 19:28:19.800: E/tt(24764): 字符:Gwidth:6

计算高度:

 FontMetrics fm = mTextPaint.getFontMetrics(); 
         Log.e("fm.ascent", fm.ascent+"");
         Log.e("fm.descent", fm.descent+"");
         Log.e("fm.bottom", fm.bottom+"");
         Log.e("fm.top", fm.top+"");
         float textheight = fm.bottom - fm.top;

2.计算字符串长度

        String text = "as我是啦啦啦的小帅哥";
        float width = paint.measureText(text);
        Log.e("tt", text + "---width:" + width);

打印结果如下:

11-15 19:28:19.800: E/tt(24764): as我是啦啦啦的小帅哥---width:122.0

3.计算最大限制长度是可以放下多少个字符

//breakText:截取字符串,截取字符串最大长度为50,不超过50时,返回截取的字符数量
        int measurennums = paint.breakText(text, true, 50, null);
        Log.e("tt", text + "---measurennums:" + measurennums);

转载务必注明出处,否则追究相关责任:
http://blog.csdn.net/u014614038/article/details/52824785

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值