3

I'm trying to set the dimensions of the image so that the width will always take up the full width of the card (minus the horizontal margin) and with a flexible height, so that it can scale as it needs to.

How can I do this? It seems that the style needs a height, it won't accept null.

I have tried a LOT of combinations using various resizeModes, heights, widths etc.

Here is the component:

enter image description here

And here is my current code:

 renderImage(image) {
    const { width, height } = Dimensions.get('window');

    if (image) {
      return (
        <View style={styles.imageContainer}>
          <Image
            style={{ width, resizeMode: 'contain', height: 300 }}
            source={{ uri: image }}
          />
        </View>
      );
    }
  }
bloppit
  • 621
  • 8
  • 22

3 Answers3

2

The aspectRatio property solves this problem nicely.

<Image
  style={{ width: '100%', aspectRatio: 1 }}
  source={{uri: 'https://online.picture/dynamic_size'}}/>
0

I had same problem for images from web (where no exact width & height was known) and created react-native-web-image. Currently not for local images, only for remote. Try it, I will be glad if it will help.

  • I can't do that I'm afraid. I'm using exponent which doesn't support native modules. – bloppit Jan 31 '17 at 16:20
  • In that case I can suggest use two-step logic: fist `Image.getSize` (https://facebook.github.io/react-native/docs/image.html#getsize) to retrieve original dimensions, then you can calculate all needed dimensions to scale properly. –  Jan 31 '17 at 16:43
0

Set the width to be the screen width, and set height to be undefined.

yedidyak
  • 1,964
  • 13
  • 26