Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native Image Height (Full Width)

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.

like image 984
Alex Curtis Avatar asked Sep 14 '16 18:09

Alex Curtis


People also ask

How do I set the width and height of an image in react?

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.

How do you give 100% width in React Native?

To set 100% width in React Native flexbox, we can set alignSelf to 'stretch' .

How do you manage the aspect ratio of an image React Native?

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.


1 Answers

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>     )   } } 
like image 94
nburk Avatar answered Sep 21 '22 17:09

nburk