Shubham Bisht
Shubham Bisht

Reputation: 687

How to fit a large Image in a View without stretching/cropping the Image in React Native?

I want to use a Image in a View without affecting its quality. I don't want to crop the Image or stretch it. I also tried using with ImageBackground.

Here is my project:

https://snack.expo.io/r1kJ_rD5V?fbclid=IwAR0CVRu3YyQnbdVo9t2Vy1ygN-fGapT5coCQe-JUARJ3KNkkFNpx0KIh-OI

How can I achieve this?

Upvotes: 1

Views: 3415

Answers (2)

sdkcy
sdkcy

Reputation: 3548

Firsly, we need to get screen dimensions for screen width;

const { width } = Dimensions.get('window');

After that, we need to specify an image canvas for drawing our images and set resizeMode = {"contain"} to maintain the image's aspect ratio.

_renderItem = item => {
  return (
    <Image
      style={{
        width: width, // We need to give specific width to place images
        height: '100%', // We need to set height to 100%
      }}
      source={item.images}
      resizeMode={'contain'}
    />
  );
};

Now we need to divide the screen height to 70:30;

return (
  <View style={styles.container}>
    <FlatList
      style={{ height: '70%' }} // We need to share the screen height with the View("A small view")
      data={images}
      renderItem={({ item }) => this._renderItem(item)}
      horizontal={true}
      showsHorizontalScrollIndicator={false}
      pagingEnabled={true}
    />
    <View style={{ height: '30%' }}>
      <Text>A small view</Text>
    </View>
  </View>
);

And last thing is to set a padding value to separate the view from status bar;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 20, // Just for iOS
  },
});

Upvotes: 2

Morsmetus
Morsmetus

Reputation: 63

did you try resizeMode="contain" or "cover"

https://facebook.github.io/react-native/docs/image.html#resizemode

Upvotes: 0

Related Questions