【问题标题】:How to get string width on Android?如何在 Android 上获取字符串宽度?
【发布时间】:2011-04-07 12:04:06
【问题描述】:

如果可能的话,我也想获得身高。

【问题讨论】:

    标签: android string bounding-box


    【解决方案1】:

    您可以使用 Paint 对象的getTextBounds(String text, int start, int end, Rect bounds) 方法。您可以使用TextView 提供的绘制对象,也可以自己构建一个具有所需文本外观的对象。

    使用 Textview,您可以执行以下操作:

    Rect bounds = new Rect();
    Paint textPaint = textView.getPaint();
    textPaint.getTextBounds(text, 0, text.length(), bounds);
    int height = bounds.height();
    int width = bounds.width();
    

    【讨论】:

    • @Frank : 如果字符串是跨区字符串怎么办?
    • 很好的答案。顺便说一下,如果调用textView.setTextSize(),结果会更准确。
    【解决方案2】:

    如果你只需要你可以使用的宽度:

    float width = paint.measureText(string);
    

    http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)

    【讨论】:

    • 另外,如果你想以一定的字体大小测量文本,你可以使用TextPaint paint = new TextPaint(); paint.setTextSize(textSize);textSize 以像素为单位。
    • 为了身高?
    【解决方案3】:

    文本有两种不同的宽度度量。一个是在宽度上绘制的像素数,另一个是在绘制文本后光标应该前进的“像素”数。

    paint.measureTextpaint.getTextWidths 返回绘制给定字符串后光标应前进的像素数(浮点数)。对于绘制的像素数,请使用其他答案中提到的paint.getTextBounds。我相信这被称为字体的“前进”。

    对于某些字体,这两个测量值不同(很多),例如字体Black Chancery 的字母超出其他字母(重叠) - 请参见大写字母“L”。使用其他答案中提到的 paint.getTextBounds 来绘制像素。

    【讨论】:

      【解决方案4】:

      我是这样测量宽度的:

      String str ="Hiren Patel";
      
      Paint paint = new Paint();
      paint.setTextSize(20);
      Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
      paint.setTypeface(typeface);
      paint.setColor(Color.BLACK);
      paint.setStyle(Paint.Style.FILL);
      Rect result = new Rect();
      paint.getTextBounds(str, 0, str.length(), result);
      
      Log.i("Text dimensions", "Width: "+result.width());
      

      这会对你有所帮助。

      【讨论】:

        【解决方案5】:

        您很可能想知道具有给定字体的给定文本字符串的绘制尺寸(即特定的Typeface,例如具有 BOLD_ITALIC 样式的“sans-serif”字体系列,以及 sp 或px)。

        您可以降低级别并直接使用Paint 对象来处理单行文本,而不是膨胀一个成熟的TextView,例如:

        // Maybe you want to construct a (possibly static) member for repeated computations
        Paint paint = new Paint();
        
        // You can load a font family from an asset, and then pick a specific style:
        //Typeface plain = Typeface.createFromAsset(assetManager, pathToFont); 
        //Typeface bold = Typeface.create(plain, Typeface.DEFAULT_BOLD);
        // Or just reference a system font:
        paint.setTypeface(Typeface.create("sans-serif",Typeface.BOLD));
        
        // Don't forget to specify your target font size. You can load from a resource:
        //float scaledSizeInPixels = context.getResources().getDimensionPixelSize(R.dimen.mediumFontSize);
        // Or just compute it fully in code:
        int spSize = 18;
        float scaledSizeInPixels = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_SP,
                    spSize,
                    context.getResources().getDisplayMetrics());
        paint.setTextSize(scaledSizeInPixels);
        
        // Now compute!
        Rect bounds = new Rect();
        String myString = "Some string to measure";
        paint.getTextBounds(myString, 0, myString.length(), bounds);
        Log.d(TAG, "width: " + bounds.width() + " height: " + bounds.height());
        

        对于多行或跨行文本 (SpannedString),请考虑使用StaticLayout,您可以在其中提供宽度并导出高度。有关在自定义视图中测量文本并将其绘制到画布的非常详细的答案,请参阅:https://stackoverflow.com/a/41779935/954643

        还值得注意的是@arberg 在下面关于绘制的像素与提前宽度的回复(“在绘制给定字符串后光标应该前进的像素数(浮点数)”),以防您需要处理。

        【讨论】:

          【解决方案6】:

          我想分享一个更好的方法(比当前接受的答案更通用)使用静态类 @987654322 获取绘制文本 (String) 的确切宽度@:

          StaticLayout.getDesiredWidth(text, textPaint))
          

          此方法比textView.getTextBounds() 更准确,因为您可以在多行TextView 中计算单行的宽度,或者您可能不使用TextView 开头(例如在自定义View 实现中) )。

          这种方式类似于textPaint.measureText(text),但在极少数情况下似乎更准确。

          【讨论】:

            【解决方案7】:

            simplay 我在一行中添加了最大字符并用最大空间挑战它并创建新行

                v_y = v_y + 30;
                String tx = "مبلغ وقدرة : "+ AmountChar+" لا غير";
            
                myPaint.setTextAlign(Paint.Align.RIGHT);
            
                int pxx = 400;
                int pxy = v_y ;
                int word_no = 1;
                int word_lng = 0;
                int max_word_lng = 45;
                int new_line = 0;
                int txt_lng = tx.length();
                int words_lng =0;
                String word_in_line = "" ;
                for (String line : tx.split(" "))
                {
                    word_lng = line.length() ;
                    words_lng += line.length() + 1;
            
                    if (word_no == 1 )
                    {word_in_line = line;
                    word_no += 1;
                    }
                    else
                        { word_in_line += " " + line;
                        word_no += 1;
                        }
            
                    if (word_in_line.length() >= max_word_lng)
                   {
                       canvas.drawText(word_in_line, pxx, pxy, myPaint);
                        new_line += 1;
                        pxy = pxy + 30;
                        word_no = 1;
                        word_in_line = "";
                    }
                    if (txt_lng <= words_lng )
                    { canvas.drawText(word_in_line, pxx, pxy, myPaint); }
                }
            
                v_y = pxy;
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-05-12
              • 2011-01-29
              • 2011-12-04
              • 1970-01-01
              • 2015-12-30
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多