Scaled images in React Native

How to scale images in React Native keeping the proportions and not affecting UX

Sharing is caring!

by German Stuarts

03/19/2018

A year ago we started implementing a new design for Keep a Breast and chose React Native to build the app for both Android and iOS. When we were working with the navigation bar, we had to add icons. All of them had the same height, but their width differed. Since the Image component of React Native forced us to set width and height, we had to set both parameters by hand for every image when one of the two was always fixed. Because of that, we needed to calculate the width automatically.

This issue is not common in web development, where images are scaled automatically. In React Native this kind of functionality doesn’t exist by default. Here’s the explanation.

In order to solve this issue for our application we created react-native-scaled-image. A module that enables us to add images defining only height or width and keeping the aspect ratio.

How the React Native Scaled Image works

This part of the code checks the origin of the image and gets its dimensions using the proper function according to the source of it:

  • If it’s a remote image (it has a URI) the method getSize from the default Image class of React Native is used.

  • If it’s a static image the function resolveAssetSource is used, since Image.getSize doesn’t work with local images.

This part of the code handles the actual dimension calculation. Using the actual size of the image and the values received by parameter, the “other” dimension is calculated, keeping the aspect ratio.

In case both width and height are set, those values are set to the state of the component. If none of them is defined, the size calculated in the previous code is the one used.

This module is brand new and we’re eager for feedback! If you have any comments, go ahead. You can also add new feature proposals using the GitHub issues!

More articles to read

Previous blog post

News

03/23/2018

Comunidad en NaNLABS – Espacio de Coworking en La Plata

Read the complete article

Next blog post

Web Technologies

03/14/2018

Native extensions for NodeJS

Read the complete article