Nicholas Summers
Nicholas Summers

Reputation: 4756

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?

Upvotes: 6

Views: 12830

Answers (2)

This is not exactly true, you are calculating an approximation of the dpi but not the actual dpi.

pixelRatio intervienes between real pixel and independent pixel:

    real pixel distance (px) = pixelRatio * independente pixel distance (dp)

exemple with Huawei Y9s (2019) metrics from https://yesviz.com/devices.php

  width in independant pixel = 360 dp
  width in real pixel = 1080 px
  density in independant pixel = 130 dip
  density in real pixel = 391 dpi
  ratio = 3
  
  the upper formula gives us: 360dp * 3 ≈ 1080px => all good    

  but ratio = 3 
  is different from : dpi / 160 = 391 /160 = 2.44

Android makes a confusion between the actual independant density and the bucket density value. (https://www.youtube.com/watch?v=zhszwkcay2A)


But the rendering is different, if you show a div of 320dp on two apple devices :

Ipad Pro 12.9'' (2020) with 132 density in independant pixels => div is printed 61mm or 2.36inch on the screen

Iphone 11 (2019) with 163 density in independant pixels => div is printed 50mm or 2inch on the screen

So technically, density independant pixel can be approximated to 160dip on every devices

And the corresponding approximation of density in real pixel : The bucket density value. Let's call it ~dpi. Can be retrieve with the pixelRatio

~dpi = pixelRatio * 160

Upvotes: 1

Danny Buonocore
Danny Buonocore

Reputation: 3777

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.

Upvotes: 14

Related Questions