Home » Android » android – Does Flexbox in React Native use dp or pixel?

android – Does Flexbox in React Native use dp or pixel?

Posted by: admin June 15, 2020 Leave a comment

Questions:

As the title mentions, I am confused about the unit of layout size values used in RN. In the documentation, there is the code below that suggests it uses dp instead of pixel as the size unit. Here the getPixelSizeForLayoutSize() function tries to convert dp values to pixel values. However, in real applications, my components get out of screen bound when not dividing the size values (height/width, etc) using PixelRatio.get(). Would really appreciate your clarification!

var image = getImage({
  width: PixelRatio.getPixelSizeForLayoutSize(200),
  height: PixelRatio.getPixelSizeForLayoutSize(100),
});
<Image source={image} style={{width: 200, height: 100}} />
How to&Answers:

React Native uses logical pixels (also know as “points” on iOS), as opposed to device pixels, at the JavaScript level. When working at the native level, you occasionally may need to work with device pixels by multiplying the logical pixels by the screen scale (e.g. 2x, 3x).

When you are working with images, you’ll want to specify their dimensions in logical pixels. Also, React Native supports fractional pixels. When you need to specify precise layouts at the granularity of device pixels, use 1 / PixelRatio.get().