如何将文本宽度(以像素为单位)转换为屏幕宽度/高度的百分比?
我正在测量字符串文本,看看是否应该添加 \n
进行换行。
我正在使用 Paint.measureText
函数,它在大多数情况下都有效,但我觉得这不准确,因为 px 不等于 dp - 我在网上看到了如何将像素转换为 dp,但我宁愿将 px 转换为屏幕尺寸的百分比,例如
如果 a
是 8 像素宽,我会怎么说:
float LetterWidthPercent = _______ //get width of character in percent of screen width
float LetterHeightPercent = _______ //get height of character in percent of screen height
这样我就可以看到:
if (LineOfTextWidth >= ScreenWidth * 0.9f) //90%
这将是一个非常有用的功能方便。
I am measuring a string text to see if I should add a \n
for wrapping.
I am using the Paint.measureText
function, and it works most of the time but it occurs to me that this isn't accurate since a px doesn't equal a dp - I've seen online how to convert pixels to dp, but instead what I would rather do is convert px to a percentage of the screen size for example
If a
is 8 pixels wide, how would I say:
float LetterWidthPercent = _______ //get width of character in percent of screen width
float LetterHeightPercent = _______ //get height of character in percent of screen height
This way I could just see:
if (LineOfTextWidth >= ScreenWidth * 0.9f) //90%
This would be an extremely useful function to have handy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将需要通过 DisplayMetrics 获取屏幕宽度,或者如何...
为了获取字符大小,请使用带有边界的绘制来计算。
characterWidth/screenWidth = characterScreenPercentage
我将其设置为双精度,但您可以轻松地将其更改为浮点数。
对于字符:
对于字符串:
You will need to get the screen width through DisplayMetrics or how ever...
For getting the character size use paint with bounds to calculate.
characterWidth/screenWidth = characterScreenPercentage
I made it a double but you can easily change it to a float.
For Characters:
For strings:
您可以在(或改为)在屏幕上绘制文本之前测量内部包含文本的 TextView。通过这种方式,您可以为 TextView 设置任何字体或文本大小,并始终知道文本在屏幕上的百分比。
You can measure a TextView with text inside before(or instead) drawing it on a screen. At this way you can set any font or textSize for TextView and always know how many percents the text will have on the screen.
您可以使用以下方法将 do 转换为 Pixel,将 Pixel 转换为 dp。
将 dp 转换为像素:
将像素转换为 dp:
You can use following methods to convert do to pixel and pixel to dp.
Convert dp to pixel:
Convert pixel to dp: