开发者

How to get string width on Android?

开发者 https://www.devze.com 2023-01-14 11:48 出处:网络
I would like t开发者_JAVA技巧o get height too if possible.You can use the getTextBounds(String text, int start, int end, Rect bounds) method of a Paint object.You can either use the paint object suppl

I would like t开发者_JAVA技巧o get height too if possible.


You can use the getTextBounds(String text, int start, int end, Rect bounds) method of a Paint object. You can either use the paint object supplied by a TextView or build one yourself with your desired text appearance.

Using a Textview you Can do the following:

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


If you just need the width you can use:

float width = paint.measureText(string);

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


There are two different width measures for a text. One is the number of pixels which has been drawn in the width, the other is the number of 'pixels' the cursor should be advanced after drawing the text.

paint.measureText and paint.getTextWidths returns the number of pixels (in float) which the cursor should be advanced after drawing the given string. For the number of pixels painted use paint.getTextBounds as mentioned in other answer. I believe this is called the 'Advance' of the font.

For some fonts these two measurements differ (alot), for instance the font Black Chancery have letters which extend past the other letters (overlapping) - see the capital 'L'. Use paint.getTextBounds as mentioned in other answer to get pixels painted.


I have measured width in this way:

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());

This would help you.


Most likely you want to know the painted dimensions for a given string of text with a given font (i.e. a particular Typeface such as the “sans-serif” font family with a BOLD_ITALIC style, and particular size in sp or px).

Rather than inflating a full-blown TextView, you can go lower level and work with a Paint object directly for single-line text, for example:

// 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());



For multi-line or spanned text (SpannedString), consider using a StaticLayout, in which you provide the width and derive the height. For 
a very elaborate answer on measuring and drawing text to a canvas in a custom view doing that, see: https://stackoverflow.com/a/41779935/954643

Also worth noting @arberg's reply below about the pixels painted vs the advance width ("number of pixels (in float) which the cursor should be advanced after drawing the given string"), in case you need to deal with that.


I'd like to share a better way (more versatile then the current accepted answer) of getting the exact width of a drawn text (String) with the use of static class StaticLayout:

StaticLayout.getDesiredWidth(text, textPaint))

this method is more accurate than textView.getTextBounds(), since you can calculate width of a single line in a multiline TextView, or you might not use TextView to begin with (for example in a custom View implementation).

This way is similar to textPaint.measureText(text), however it seems to be more accurate in rare cases.


simplay i tack max charcter in the line and defieded it with max space and create new line

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

精彩评论

暂无评论...
验证码 换一张
取 消