How to use React Native PixelRatio utility class?

14.5k views Asked by At

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?

4

There are 4 answers

0
Marianna Panteli On

You could do something like:

footerNavText: {
  padding: PixelRatio.get()*3,
  fontSize: PixelRatio.get()*4
}

Check what get() method returns for each of the devices you wish to use and style accordingly. For more info visit https://facebook.github.io/react-native/docs/pixelratio.html

3
dblackker On

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

0
ashuvssut On
// create this utils.ts file
import { PixelRatio } from "react-native";

// dp(123) converts 123px (px as in your mockup design) to dp.
export const dp = (px: number) => {
    return px / PixelRatio.get();
};

// sp(54) converts 54px (px as in your mockup design) to sp
export const sp = (px: number) => {
    return px / (PixelRatio.getFontScale() * PixelRatio.get());
};

Use it like the following way in your styles

const styles = StyleSheet.create({
  footerNavText: {
    padding: dp(123),
    fontSize: sp(54)
  }
})

Note

Do not use dp for fontSize. dp just depends on device screen density (dpi)

sp is used for fontSize only. sp is also just like dp but the difference is that it also depends on user's font settings in his device along with the device screen density (dpi).

0
Pencilcheck On
import { PixelRatio } from "react-native";

// Testing phone's pixel density as base
const basePixelDensity = 2.8125
const baseFontScale = 1.2

export const sp = (px: number) => {
  // the higher the font scaling the more we divided by it
  // the higher the pixel density compare to our base pixel density, the more we increase font size (or decrease if the pixel density is lower)
  return px / ((PixelRatio.getFontScale() / baseFontScale) * basePixelDensity) * (PixelRatio.get() / basePixelDensity);
};

Set your own base density and font scale, worked for me