I want a React Native Image to have a width of 50% of the available screen-width, no modification to width:height ratio of the image.
Any hints how to solve this?
Doing it the React way * using JavaScript division syntax. So, to get a 16:9 ratio, * simply pass `ratio={16/9}`. * width / height, so we need to invert it.
To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.
So all we need to do is create a View with width: "100%" , then use onLayout to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.
Therefore, to make the images responsive we can simply set the value of height and width to 100% and resize mode to cover. By setting the Image's height and width to 100% and resize mode to cover, the image will proportionately occupy a 100% of the container's real estate inside of the X and Y-Axis or the container.
Local images can be rendered without giving a fixed width and height but, for remote images you must provide dimensions as react-native cant calculate them on runtime. So, the following works for me
<View style={styles.thumbContainer}>
<Image source={{uri: "REMOTE_IMAGE_URI}} style={styles.thumbnail} />
</View>
and apply following styles.
thumbContainer: {
width: '100%',
height: 400,
},
thumbnail: {
flex: 1,
width: undefined,
height: undefined,
resizeMode: 'cover'
},
Use resize mode cover
and set the width to ScreenWidth / 2 you can retrive the screen width using Dimensions component
//Get screen width using Dimensions component
var {width} = Dimensions.get('window');
//....
//In image style
image:{
width: width * 0.5
}
//In render function
<Image resizeMode = 'cover' style = {styles.image}/>
Edit adding overflow
//add overflow : visible
<Image resizeMode = 'cover' style = {[styles.image,{overflow: 'visible'}]}/>
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