Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: measureText() Return Pixels Based on Scaled Pixels

So I use Paint's measureText() method to measure the width of a segment of text, but I wanted to measure text based on a certain text size. Say I wanted to get the width of a text segment that will be 20 scaled pixels when it occupies a certain TextView. I tried the following:

Paint paint = new Paint();
paint.setTextSize(20);
paint.measureText("sample text");

However, it does not seem to be working. I believe it is returning a width with respect to a smaller text size. I feel like I'm missing something that will make me slap myself in the face and yell herp derp.

like image 746
Vinay Avatar asked Jun 03 '11 20:06

Vinay


2 Answers

You need to get the densityMultiplier like so:

final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
final float scaledPx = 20 * densityMultiplier;
paint.setTextSize(scaledPx);
final float size = paint.measureText("sample text");
like image 119
Caspar Harmer Avatar answered Sep 19 '22 21:09

Caspar Harmer


I do something like this when I have to.

int textSize = 20;
for(int i = 2; i<18 && curTextSize< textSize;i+=2)
{
    this.label.setTextSize(i);
    curTextSize = this.label.getPaint().measureText(this.label.getText().toString());
}
like image 36
madmik3 Avatar answered Sep 17 '22 21:09

madmik3