I have an image that I pull down from a url. I do not know the dimensions of this image ahead of time.
How do I style / layout the <Image/>
so it is the full width of the parent view and the height is calculated so that the aspect ratio is maintained?
I have tried using onLoad
in 0.34.0-rc.0 and the height / width are both 0 in event.nativeEvent.source
.
The image is in a <ScrollView/>
. I am not after a full screen image.
To set image width to be 100% and height to be auto in React Native, we can set the width and height of the Image . to call Dimensions. get with 'window' to get the window's dimension. Then we calculate the ratio between the width and height of the image with win.
To set 100% width in React Native flexbox, we can set alignSelf to 'stretch' .
To maintain aspect ratio of image with full width in React Native, we can set the aspectRatio style property. to add an Image with the width set to '100%' . And we set the height to undefined to keep the aspect ratio and set the aspectRatio property to set the aspect ratio of the image.
My use was very similar in that I needed to display an image with full screen width but maintaining its aspect ratio.
Based on @JasonGaare's answer to use Image.getSize()
, I came up with the following implementation:
class PostItem extends React.Component { state = { imgWidth: 0, imgHeight: 0, } componentDidMount() { Image.getSize(this.props.imageUrl, (width, height) => { // calculate image width and height const screenWidth = Dimensions.get('window').width const scaleFactor = width / screenWidth const imageHeight = height / scaleFactor this.setState({imgWidth: screenWidth, imgHeight: imageHeight}) }) } render() { const {imgWidth, imgHeight} = this.state return ( <View> <Image style={{width: imgWidth, height: imgHeight}} source={{uri: this.props.imageUrl}} /> <Text style={styles.title}> {this.props.description} </Text> </View> ) } }
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