Android:measureText()根据缩放像素返回像素
所以我使用Paint的measureText()方法来测量一段文本的宽度,但我想根据一定的文本大小来测量文本。假设我想获取一个文本段的宽度,当它占据某个 TextView 时,该宽度将是 20 个缩放像素。我尝试了以下方法:
Paint paint = new Paint();
paint.setTextSize(20);
paint.measureText("sample text");
但是,它似乎不起作用。我相信它返回的是相对于较小文本大小的宽度。我觉得我错过了一些东西,这些东西会让我打自己的脸并大喊“疱疹德普”。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要像这样获得密度乘数:
You need to get the densityMultiplier like so:
当我必须的时候我会做这样的事情。
I do something like this when I have to.
我没有足够的声誉点来评论答案,但参考 @schwiz 和 @AndreasEK 对已接受答案的评论:
measureText()
以及getTextBounds(),不包括填充,因此问题的解决方案可能是添加左右填充(或开始和结束填充)
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 withgetTextBounds()
, 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)试试
这为我解决了问题。
Try
That solved the problem for me.