Skip to content

Instantly share code, notes, and snippets.

@AshCoolman
Created August 21, 2018 10:50
Show Gist options
  • Save AshCoolman/beb94d070d55f1425f11d173a370084e to your computer and use it in GitHub Desktop.
Save AshCoolman/beb94d070d55f1425f11d173a370084e to your computer and use it in GitHub Desktop.
Device-independent pixels and React Native

Introduction

React Native dimensions are unitless & represent density-independent pixels (abstract pixels, representing a physical distance on the device)

Density-independent pixel (dp)

WARNING: DP (or DiP) not DPI

DP units keep _things roughly the same physical size

Virtual pixel unit - equivalent to 1 physical pixel on a 160dpi screen (in android),

e.g. Human fingertip is ~50dp wide

The equation

For android:

... px         ... dpi
___     X      _______
... dp         160 dpi

For Windows, same but 1dp = 1/96th inch

Conventions

dpi          name    scale
___        ______    _____
160          MDPI     1.0x
240          HDPI     1.5x
320         XHDPI     2.0x
480        XXHDPI     3.0x

React Native

Autorounding of layout

Auto rounding on native thread (relative to root)

Workflow w/sketch & xcode

Click background and get size e.g. size: iPhone 8 (375 x 667)

Go into Xcode, change simulator to match

PixelRatio

Fetching images

Provide a higher-res image on hi-pixel-density device

Good rule of thumb:

Size of image X pixel Ratio

Convert layout size (dp) to pixel size

on a device with a PixelRatio of 3 PixelRatio.roundToNearestPixel(8.4) = 8.33, which corresponds to exactly (8.33 * 3) = 25 pixels

Resources

https://developer.android.com/guide/practices/screens_support#dips-pels https://blogs.msdn.microsoft.com/text/2009/12/11/wpf-text-measurement-units/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment