Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Image fill parent, but keep ratio in react-native (dynamic/network images)

I want my image to fit as best as possible into it's 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

like image 711
Laurents Mohr Avatar asked Jan 02 '23 17:01

Laurents Mohr


2 Answers

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;
like image 119
Yusuf Siregar Avatar answered Jan 13 '23 21:01

Yusuf Siregar


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,
  },
like image 21
vemund Avatar answered Jan 13 '23 20:01

vemund