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.
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>
)
}
}