Get screen DPI in react native

我们两清 提交于 2020-08-05 08:06:46

问题


Context:

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.

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.

Problem:

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.

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?


回答1:


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).

On an mdpi screen:

1 inch = 160 pixels
1 inch = 2.54 cm
-----------------------
1 cm = 62.992126 pixels

So to render something 3cm wide on this screen, it will need to be 189 pixels.

Likewise, on an xhdpi screen (PixelRatio.get() = 2) for example:

1 inch = 320 pixels
1 inch = 2.54 cm
-----------------------
1 cm = 125.98425 pixels

Something 3cm wide will have to be 378 pixels.



来源:https://stackoverflow.com/questions/56451288/get-screen-dpi-in-react-native

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!