Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate string font width in pixels?

Tags:

java

android

I want to calculate string font width in pixels in android. I am having string array and I am appending all these array elements to form one string. so I have to set fixed spacing in between two consecutive array element.i am placing this final string into textview. Finally I am adding this textview to tablerow. In short i want to view table structure with title and values. I have seen many post over here but not getting solution for this.

Thanks in advance...!!!

like image 738
Balaji Khadake Avatar asked Jun 15 '11 15:06

Balaji Khadake


2 Answers

Looks like there is a measureText method available on Paint. I also found an example:

mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setTextSize(64);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
// ...
float w = mPaint.measureText(text, 0, text.length());
like image 78
jakebasile Avatar answered Oct 05 '22 16:10

jakebasile


Thanks Jake for the working solution, yet I found this to work for me too:

someText = "Lorem Ipsum";
TextView myTextView = (TextView) findViewById(R.id.myTextView);
float w = myTextView.getPaint().measureText(someText);

Getting the Paint directly from the TextView that I'm going to work with makes me feel that the anwser will be more accurate.

like image 29
Voy Avatar answered Oct 05 '22 17:10

Voy