Image 'contain' resizeMode not working in react native

user3621841 picture user3621841 · Apr 5, 2016 · Viewed 60.2k times · Source

I am using React Native on a real Android device. When creating a really simple app with just the following render function on the main app component...

render() {
  <Image
    source={{uri:'http://resizing.flixster.com/DeLpPTAwX3O2LszOpeaMHjbzuAw=/53x77/dkpu1ddg7pbsk.cloudfront.net/movie/11/16/47/11164719_ori.jpg'}}
    style={
      {
        flex: 1,
        resizeMode: 'contain',
        backgroundColor: 'yellow'
      }          
    } />
}

I get the following result on my device: screenshot_2016-04-05-11-05-41

As you can see the whole background is yellow so that tells us the image element is taking the whole screen size indeed. But it is just rendered wrong. The 'cover' resizeMode does work as expected (and so does the 'stretch' mode). It is the 'contain' mode that is not working (the most important one from my point of view). The problem gets even worse when placing the image on a ListView since the image does not even show.

UPDATE 1 As Frederick points out, 'contain' only works when the image is larger than the container size. So how can we make the image take the whole container size while keeping its aspect ratio? Percentages are not supported yet by styles in React, and I don't know how to get the image width and height properties once the image is loaded. None of the events associated with the Image component provide that info.

UPDATE 2 Good news. I am now using React Native v0.24.1 and it seems the image 'contain' mode now works as expected, even when the actual image size is smaller than its container. zvona's solution is good (although you need to bear in mind that onLayout will give you the image view size the image is rendered in, but NOT the actual image size being loaded). As for now, I don't know of any way to find out the actual image size (let's suppose you are retrieving the image from a network resource and you don't know the size, which could be very important if you want to calculate its aspect ratio).

Answer

Sagar Chavada picture Sagar Chavada · Nov 15, 2018

This is the latest solution:

Image.resizeMode.contain is not working with latest version of react native so i use it like this:

import ImageResizeMode from 'react-native/Libraries/Image/ImageResizeMode'

<Image source={image} resizeMode={ImageResizeMode.contain} />