Toygirl
Toygirl

Reputation: 79

Android.how to calculate the wide of string?

MY code is

 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;

I want to get the width of string ,but the return result has errors with TextView.

Don't know the right way.

thanks.

I show it in the virtual machine.

Upvotes: 0

Views: 526

Answers (4)

Winnie
Winnie

Reputation: 769

you can try to use canvas,Once a time I found the Textview can't show my text in right size ,so I use Canvas draw the text out ,the I get the width I want,that's maybe some wrong cause by dp,sp or px.

Upvotes: 1

Ravi
Ravi

Reputation: 2367

you can measure it by calling the measureText() of paint class here is the code for that-

Paint p=new paint();

int value = p.measureText("give input string to measure");

Upvotes: 0

jeet
jeet

Reputation: 29199

To calculate text width you should use:

public float measureText (String text)

method in class Paint, it will return measured width of text in paint.

Upvotes: 2

Trần Sĩ Long
Trần Sĩ Long

Reputation: 477

you can use:

int width = paint.measureText("this text");

measureText(String text) will return width of text.

Upvotes: 1

Related Questions