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:
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).
To fit an Image to the full width of the screen and maintain aspect ratio with React Native, we can set the width to null and the height to the height we want. to set the height of the Image to 300 and the width to null to fit the Image to make the width flexible and maintain aspect ratio.
Adding Image Let us create a new folder img inside the src folder. We will add our image (myImage. png) inside this folder. We will show images on the home screen.
aspectRatio Aspect ratio controls the size of the undefined dimension of a node. See https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio for more details. On a node with a set width/height, aspect ratio controls the size of the unset dimension.
This is the trick:
render() { return ( <Image style={{ flex: 1, height: undefined, width: undefined }} source={require("../../resource/image/bg_splash.jpg")} resizeMode="contain" /> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With