Reputation: 78
I want my image to fit as best as possible into its 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
Upvotes: 6
Views: 17687
Reputation: 353
Setting the image resizeMode which can either be - contain, cover, stretch, center, repeat, will do the trick
<Image
alt="image Not find"
source={require("./path/to/image.jpeg")}
style={{resizeMode: 'contain' }}
/>
Upvotes: 0
Reputation: 106
React Next set up for an image that fills its parent container:
image={
<Image
src="https://picsum.photos/1174/611?random=65411"
alt="mandatory alt text goes here"
quality={100}
layout="fill"
/>
}
Upvotes: 0
Reputation: 118
This styling works for me:
image: {
flex: 1,
resizeMode: "contain",
},
:shipit:
Upvotes: 0
Reputation: 78
While the solutions posted above work for local images, they don't work for network images. Here is why: https://facebook.github.io/react-native/docs/images#why-not-automatically-size-everything
The simplest solution for me was to calculate the height off my component based on the Dimensions height and the flex-portion my component takes in the view.
E.g. in my view the image component has a .85 flex, in a parent that has a 1 flex.
So 100% height of the parent equals to:
Dimensions.get('window').height * 0.85
Upvotes: 0
Reputation: 139
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;
Upvotes: 13
Reputation: 1817
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,
},
Upvotes: 3