5

I want my image to fit as best as possible into its parent, while keeping its width/height ratio. I fetch the image at runtime, so I don't know the width/height of my images beforehand, so it needs to be dynamic.

In the web I can achieve this with:

.image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

This is how it should look like (simplified):
https://codepen.io/laurentsmohr/pen/OBEGRG?fbclid=IwAR1-dFcTC7vvXwd0m2NTeCMxm6A6Uzv0lFx2UUCNpgFnpSgEm9aHhr14LK4

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Laurents Mohr
  • 68
  • 1
  • 1
  • 6

5 Answers5

8

According to this official React-Native guide, if you want to make an image scale dynamically according to its parent element dimensions, you have to set the width and height of the image to undefined, and perhaps also add resizeMode="contain" to the image props. You can use this following styling to your image:

import { StyleSheet, Dimensions } from 'react-native;

// Get device width
const deviceWidth = Dimensions.get('window').width;

/*
image container dimension is dynamic depending on the device width
image will dimension will follow imageContainer's dimension
*/
const styles = StyleSheet.create({
  imageContainer: {
    height: deviceWidth * 0.8,
    width: deviceWidth * 0.8
  },
  image: {
    flex: 1,
    height: undefined,
    width: undefined
  }
});

export default styles;
1

I always use StyleSheet.absoluteFillObject. It will fill the parent's size. resizeMode can be contain, cover, stretch, center, repeat. Like this:

  image: {
    resizeMode: 'cover',
    ...StyleSheet.absoluteFillObject,
  },
vemund
  • 1,667
  • 4
  • 29
  • 43
0

While the solutions posted above work for local images, they don't work for network images. Here is why: https://facebook.github.io/react-native/docs/images#why-not-automatically-size-everything

The simplest solution for me was to calculate the height off my component based on the Dimensions height and the flex-portion my component takes in the view.
E.g. in my view the image component has a .85 flex, in a parent that has a 1 flex. So 100% height of the parent equals to:

Dimensions.get('window').height * 0.85
Laurents Mohr
  • 68
  • 1
  • 1
  • 6
0

This styling works for me:

 image: {
    flex: 1,
    resizeMode: "contain",
  },

:shipit:

Marc
  • 101
  • 1
  • 5
0

React Next set up for an image that fills its parent container:

  image={
          <Image
            src="https://picsum.photos/1174/611?random=65411"
            alt="mandatory alt text goes here"
            quality={100}
            layout="fill"
          />
        }
Dean Miranda
  • 106
  • 3