在React Native中获取屏幕DPI [英] Get screen DPI in react native
问题描述
上下文:
我正在尝试创建一个能够使用真实尺寸的应用程序。在我的特定情况下,如果不是100%准确,那就可以了;但是,越精确越好。
I am trying to create an app that is able to use real world dimensions. In my particular case, it is OK if it's not 100% accurate; however, the more accurate the better.
例如:如果我尝试显示一个3厘米宽的正方形,而实际上我显示一个2.8厘米宽的正方形,那是可以接受的。
For example: If I am trying to display a 3cm wide square and in actuality I display a 2.8cm wide square, that is acceptable.
问题:
虽然似乎存在获取屏幕屏幕的方法宽度和高度(以像素为单位),则无法获取屏幕DPI或屏幕的宽度&高度,以厘米/英寸为单位。
While there appears to be ways to get a screen's width & height in pixels, there is no way to get either the screen DPI or the screen's width & height in cm/in.
我的问题:如何获取或计算屏幕的DPI?如果无法做到这一点,还有另一种方法可以尝试使用真实的测量结果吗?
My Question: How can I get or calculate the screen's DPI? If this isn't possible, is there another way to try and use a real world measurement?
推荐答案
您可以尝试使用React Native的 PixelRatio.get()进行计算。此方法将返回一个乘数,其中 1
等于一个mdpi屏幕( 160 dpi
)。因此,如果 PixelRatio.get()
返回 1.5
,则其为hdpi屏幕( 160 * 1.5 = 240 dpi
)。
You could try using React Native's PixelRatio.get() to calculate this. This method will return a multiplier with 1
equalling an mdpi screen (160 dpi
). So if PixelRatio.get()
returns 1.5
, then its an hdpi screen (160 * 1.5 = 240 dpi
).
在mdpi屏幕上:
1 inch = 160 pixels
1 inch = 2.54 cm
-----------------------
1 cm = 62.992126 pixels
因此,要在此屏幕上渲染3cm宽的内容,同样是189像素。
So to render something 3cm wide on this screen, it will need to be 189 pixels.
同样,在xhdpi屏幕上( PixelRatio.get()= 2
):
Likewise, on an xhdpi screen (PixelRatio.get() = 2
) for example:
1 inch = 320 pixels
1 inch = 2.54 cm
-----------------------
1 cm = 125.98425 pixels
3厘米宽的东西必须为378像素。
Something 3cm wide will have to be 378 pixels.
这篇关于在React Native中获取屏幕DPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!