所以我用画图的measureText()方法来测量文本段的宽度,但我想根据一定的文本大小来衡量的文字。说我希望得到一个文本段,这将是20缩放像素时占有一定的TextView的宽度。我试过如下:
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");
不过,它似乎并不奏效。我相信它返回的宽度相对于较小的文本大小。我觉得我失去了一些东西,这将使我拍自己的脸,并大叫HERP DERP。
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.
您需要得到densityMultiplier像这样:
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");