1

Possible Duplicate:
How to get string width on Android?

I use the following code to calculate the width of the string, but the result of the width is considerably different from the width which displayed in TextView. How can I make this correctly? Thanks in advice.

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;
Community
  • 1
  • 1
Li Che
  • 727
  • 10
  • 24
  • [Duplicated](http://stackoverflow.com/q/3630086/1050058). You guys should flag duplicated to encourage new guys search before asking. – Trung Nguyen Nov 01 '12 at 08:11

2 Answers2

5

i think try this code for width of string

float width = paint.measureText(string);
ckpatel
  • 1,926
  • 4
  • 18
  • 34
4

Try this code, I hope it will help you..

Paint paint= new Paint(); 
paint.setTextSize(size);
int txtWidth = (int)(paint.measureText("Hello how are you?"));
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133