Android: measureText() Return Pixels Based on Scaled Pixels

馋奶兔 提交于 2019-12-17 10:49:10

问题


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.


回答1:


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



回答2:


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



回答3:


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;



回答4:


Try

Paint.SetLinearText(true)

That solved the problem for me.



来源:https://stackoverflow.com/questions/6232541/android-measuretext-return-pixels-based-on-scaled-pixels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!