Nuthinking
Nuthinking

Reputation: 1321

Native pixels size (how to ignore pixel ratio)

For a simple project which will be deployed to specific devices, I am wondering if it is possible to specify measurements using native pixels, hence ignoring the device dpi (which could be, for instance, overridden by the user in Windows at system level).

Currently, the only solution seems to divide any value for pixel ratio.

Is there a simpler hence more manageable way?

Upvotes: 0

Views: 686

Answers (1)

ide
ide

Reputation: 20788

React Native comes with a PixelRatio module that has a method called get. You must manually divide all of your measurements by the pixel ratio.

  1. Start with the number of physical pixels.
  2. Divide it by the pixel ratio (PixelRatio.get()) to get the corresponding number of logical pixels.
  3. Use the number of logical pixels in StyleSheet.create and other layout-related methods.
  4. React Native and the underlying native UI frameworks will convert the logical pixels back to physical pixels.

You could write a helper method for this if it were to get tedious. This is an idea for an API:

StyleSheet.create({
  box: {
    width: physical(100),
    height: physical(75),
  },
});

Most of the time though you should work with logical pixels. It's only when you want to precisely control the hardware screen or are interacting with a system without a notion of screen scale (e.g. fetching a JPEG image) that you'd want to work with physical pixels.

Upvotes: 1

Related Questions