Search code examples
react-nativedpi

Get screen DPI in react native


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?


Solution

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