Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image resizeMode='contain' not working in React Native

Here's the simplest code possible:

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Image resizeMode={'contain'} source={imageSource}/>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

If the resizeMode is set on 'center', it's working nearly as expected, but when in 'contain', the image does not resize. The image is really huge, but it does not resize... Where am I wrong? :)

like image 213
ghivert Avatar asked May 09 '18 16:05

ghivert


People also ask

How do I use aspect ratio in 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.

How do I change the size of an image in React Native?

To resize local image files, we created react-native-image-resizer. Give it the path of an image and new dimensions and it will generate a new image with these dimensions. You can use an image from the camera roll or a base64 encoded image.


2 Answers

Your image does not have the context of height and width. You need to specify it.

This should fix your issue:

 <Image
style={{ width: "100%", height: "100%" }}
resizeMode={"contain"}
source={imageSource}
/>;
like image 90
ReyHaynes Avatar answered Oct 14 '22 23:10

ReyHaynes


If you want that your image to be as width as your page you can use the code below:

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Image
          style={styles.image}
          resizeMode={'contain'}
          source={imageSource}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});
like image 35
Vahid Boreiri Avatar answered Oct 14 '22 23:10

Vahid Boreiri