Android: measureText() Return Pixels Based on Scaled Pixels Android: measureText() Return Pixels Based on Scaled Pixels android android

Android: measureText() Return Pixels Based on Scaled Pixels


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


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


I don't have enough reputation points to comment on answers but in reference to the comments by @schwiz and @AndreasEK on the accepted answer:

measureText(), along with getTextBounds(), does not include padding so it's possible that the solution to their problem is to add the left and right padding (or start and end padding)

final float scaleFactor = getContext().getResources().getDisplayMetrics().density;final float scaledPx = 20 * scaleFactor;paint.setTextSize(scaledPx);final float padding = scaleFactor * (textView.getPaddingStart() + textView.getPaddingEnd());final float size = paint.measureText("sample text") + padding;