Search code examples
reactjsreact-nativereact-native-image

React Native: Image "contain" is behaving the same as "cover"


I have the following image that I want to sit as a header in my React Native app:

enter image description here

I want all the text in my <ScrollView> to flow behind that header. I've been able to do this with the following code:

import React, { Component } from 'react';
import { Text, View, ScrollView, ImageBackground} from 'react-native';

export default class Login extends Component {
  render() {
    return (
      <View style={{
          flex: 1,
          justifyContent: "center",
          alignItems: "center"
        }}>
          <View
            style={{
              position: "absolute",
              width: "100%",
              top: 0
            }}
          >
            <ImageBackground
              source={require('../../images/swoord-top.png')}
              style={{
                flex: 1,
                resizeMode: "contain",
                justifyContent: 'center'
              }}
            >
              <View style={{
                backgroundColor: 'green',
                height: 500,
                width: 25
              }}></View>
            </ImageBackground>
          </View>
        <ScrollView style={{backgroundColor: 'pink', zIndex: -1}}>
        <Text style={{fontSize: 42}}>
          Lorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolorLorem ipsum dolor
        </Text>
      </ScrollView>
      </View>
    );
  }
}

This looks like this:

enter image description here

The green bar on the lefthand side defines the height of the header. The problem is that the <BackgroundImage> stretches to fit the header container vertically, and spills out the sides, even though I've specified resizeMode: cover.

What I Want To Know:

How do I make the background image compress to fit in the screen horizontally?


Solution

  • <ImageBackground /> does not work as <Image /> so resizeMode contain will not work, you can either give fixed height and width to the parent view of <ImageBackgroud/> or you can use <Image /> with position absolute to achieve this.