Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React Native PixelRatio utility class?

I have an app written initially for iPhone 6 symulator which has a componend syled with following example values:

const styles = StyleSheet.create({
  headerNav: {
    width: 40,
    height: 40
  },
  headerLogoImage: {
    width: 140,
    height: 140
  },
  footerNavText: {
    padding: 15,
    fontSize: 25
  }
});

Unfortunately when I launched the app on iPad symulator, the size proportions completely collapsed. I know that there is something like PixelRation but documentation is very limited and unclear.

Any idea / suggestions how can I translate these width / height / padding & fontSize to proper values using this PixelRatio class?

like image 952
damax Avatar asked Mar 09 '16 22:03

damax


People also ask

How do you use PixelRatio in React Native?

Rounds a layout size (dp) to the nearest layout size that corresponds to an integer number of pixels. For example, on a device with a PixelRatio of 3, PixelRatio. roundToNearestPixel(8.4) = 8.33 , which corresponds to exactly (8.33 * 3) = 25 pixels.

How do I use dp in React Native?

With density independent pixels (dp), React Native defines a coordinate space separate from the resolution of the device. This makes it much more simpler to place items. An item of 300(dp) in width, will generally cover the same amount of space no matter the screen size, even if the resolution of the devices varies.

How do you get screen density in React Native?

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.

How do you change the font size in PX in React Native?

You need to use fontSize attribute/property of stylesheet design, in order to set text font size in your Text component. Set Fontsize in react native application : Using below CSS properties you can set font size in your react native application.


1 Answers

fontSize needs to be divided by PixelRatio.getFontScale(). This will account for different screen densities in iOS and Android.

footerNavText: {
  fontSize: 25 / PixelRatio.getFontScale()
}

https://facebook.github.io/react-native/docs/pixelratio.html

like image 177
dblackker Avatar answered Sep 19 '22 15:09

dblackker