I want my image to fit as best as possible into it's parent, while keeping its width/height ratio. I fetch the image at runtime, so I don't know the width/height of my images beforehand, so it needs to be dynamic.
In the web I can achieve this with:
.image {
width: 100%;
height: 100%;
object-fit: contain;
}
This is how it should look like (simplified):
https://codepen.io/laurentsmohr/pen/OBEGRG?fbclid=IwAR1-dFcTC7vvXwd0m2NTeCMxm6A6Uzv0lFx2UUCNpgFnpSgEm9aHhr14LK4
According to this official React-Native guide, if you want to make an image scale dynamically according to its parent element dimensions, you have to set the width and height of the image to undefined, and perhaps also add resizeMode="contain" to the image props. You can use this following styling to your image:
import { StyleSheet, Dimensions } from 'react-native;
// Get device width
const deviceWidth = Dimensions.get('window').width;
/*
image container dimension is dynamic depending on the device width
image will dimension will follow imageContainer's dimension
*/
const styles = StyleSheet.create({
imageContainer: {
height: deviceWidth * 0.8,
width: deviceWidth * 0.8
},
image: {
flex: 1,
height: undefined,
width: undefined
}
});
export default styles;
I always use StyleSheet.absoluteFillObject
. It will fill the parent's size. resizeMode
can be contain, cover, stretch, center, repeat
. Like this:
image: {
resizeMode: 'cover',
...StyleSheet.absoluteFillObject,
},
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