3

I am implementing a "ruler" feature to my app and it is critical that the ruler size/scale, in centimeters, is consistent across multiple devices. That is, 1 'tick' must be always equal to 1 centimenter. Howerver I have not found in any documentation a way to size components using real-world units (cm, inch) like you can do in CSS; Nor have I found a way to accurately get the screen size (in inches or cm) or DPI.

Is there a way to use cm/inches in React Native or get the REAL screen DPI?

Pedro Affonso
  • 1,656
  • 15
  • 26

2 Answers2

2

1 inch = 160 dp (Always)

Note that 1 inch is ALWAYS 160dp, independent of screen size. A dp(density-independent pixels) is a physical distance of 1/160th of an inch.

React-Native uses dp(density-independent pixels) as the unit in styling.

So, if you write:

<View style={{ height: 160, width:160, backgroundColor: 'red }}>
</View>

This gives you a red block of 1 inch X 1 inch

Vipul
  • 734
  • 1
  • 10
  • 27
  • Actually that's the problem, 160 dp is not always 1 inch in react native. In my test device I get 1 inch ~= 140 dp – Pedro Affonso Apr 25 '21 at 15:13
  • @PedroAffonso are you testing on a simulator? If so the dimensions of the simulator might not up to scale. – Vipul Apr 25 '21 at 15:24
1

Dimensions properties in react native are unitless, so those properties are not available in ReactNative. The best you can do is use PixelRatio's getPixelSizeForLayoutSize() which is documented here: https://reactnative.dev/docs/pixelratio#getpixelsizeforlayoutsize

You would need to also have the pixel density (dpi) for your solution, and the formula: https://www.pixelto.net/px-to-cm-converter

You still might run into some weird situations where pixels are split in half and other rounding errors as you're trying to fit 1cm into tiny pixels on the screen that may not always equal to 1cm, due to physical limitations.

mikep17
  • 75
  • 5