【问题标题】:How to calculate the width of the string [duplicate]如何计算字符串的宽度[重复]
【发布时间】:2012-11-01 06:17:41
【问题描述】:

可能重复:
How to get string width on Android?

我使用下面的代码来计算字符串的宽度,但是宽度的结果与TextView中显示的宽度有很大的不同。我怎样才能正确地做到这一点?感谢您的建议。

Paint paint= new Paint(); 
        paint.setTextSize(size);


        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;

【问题讨论】:

  • Duplicated。你们应该在询问之前标记重复以鼓励新人搜索。
  • 非常感谢您提供的链接。下次我会非常仔细地搜索。

标签: android


【解决方案1】:

我想试试这个代码的字符串宽度

float width = paint.measureText(string);

【讨论】:

    【解决方案2】:

    试试这个代码,希望对你有帮助..

    Paint paint= new Paint(); 
    paint.setTextSize(size);
    int txtWidth = (int)(paint.measureText("Hello how are you?"));
    

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 2018-08-31
      • 2019-04-08
      • 1970-01-01
      • 2011-07-19
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多