React Native: Resize an image and put it in the top of the screen

223 Views Asked by At

I want to resize the image to fit my desired width and height and put it in the top. This is my code:

    <View style={{ flex: 1 }}>
      <Image source={TOP_START_GRAPHIC} style={styles.topStartImage} />
      // another contents goes here...
    </View>

style:

const styles = StyleSheet.create({
  topStartImage: {
    resizeMode: "contain",
    width: screen.width * 0.6,
    height: screen.height * 0.4,
    backgroundColor: 'green',
  },
})

this is the result: the result

I found out that it happens because I set the resizeMode: "contain" so that it puts the mage in the center. But if I dont set it, the image will be cropped and super zoom like this: if I don't resize the image

I expect it to be in the top of the screen with the image fully shown like the first image. Can you help me?

1

There are 1 best solutions below

2
Bala Vigness On

Wrap the image inside a View like this ,

<View style={{ flex: 1 }}>
  <View style={styles.topStartContainer}>
    <Image source={TOP_START_GRAPHIC} style={styles.topStartImage} resizeMode="contain" />
  </View>
  {/* Other contents go here */}
</View>

After that give styling for this container as ,

const styles = StyleSheet.create({
  topStartContainer: {
    justifyContent: 'flex-start',
    alignItems: 'center',
    paddingTop: 20, // Adjust this value as needed to set the desired spacing
  },
  topStartImage: {
    width: '60%',
    aspectRatio: 1, // Maintain the original aspect ratio of the image
    backgroundColor: 'green',
  },
});

This can hold your image in your desired location (In your case center).