Android:measureText()基于缩放像素返回像素

Vin*_*nay 17 android paint text-size

所以我使用Paint的measureText()方法来测量一段文本的宽度,但我想根据特定的文本大小来测量文本.假设我想要获得文本片段的宽度,当它占用某个TextView时,它将是20个像素的像素.我尝试了以下方法:

Paint paint = new Paint();
paint.setTextSize(20);
paint.measureText("sample text");
Run Code Online (Sandbox Code Playgroud)

但是,它似乎没有起作用.我相信它会返回相对于较小文本大小的宽度.我觉得我错过的东西会让我在脸上拍打自己,然后大喊大叫.

Cas*_*mer 38

你需要像这样得到densityMultiplier:

final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
final float scaledPx = 20 * densityMultiplier;
paint.setTextSize(scaledPx);
final float size = paint.measureText("sample text");
Run Code Online (Sandbox Code Playgroud)