zoukankan      html  css  js  c++  java
  • Android drawText获取text宽度的三种方式

    String str = "Hello";
    canvas.drawText( str , x , y , paint);

    //1. 粗略计算文字宽度
    Log.d(TAG, "measureText=" + paint.measureText(str));

    //2. 计算文字所在矩形,可以得到宽高
    Rect rect = new Rect();
    paint.getTextBounds(str, 0, str.length(), rect);
    int w = rect.width();
    int h = rect.height();
    Log.d(TAG, "w=" +w+"  h="+h);

    //3. 精确计算文字宽度
    int textWidth = getTextWidth(paint, str);
    Log.d(TAG, "textWidth=" + textWidth);

        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;
        }

  • 相关阅读:
    react 性能优化
    JS获取当前网页大小以及屏幕分辨率等
    创建对象的6种方式总结
    版本号规则
    JS事件模型
    浅谈虚拟DOM
    浏览器的回流与重绘
    JavaScript预编译
    canvas学习笔记
    java、tomcat安装
  • 原文地址:https://www.cnblogs.com/zhongle/p/4046330.html
Copyright © 2011-2022 走看看