Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stretch a static image as background in React Native?

Tags:

react-native

I'd like to use a background image in my react native app, the image is smaller than the screen, so I have to stretch it.

but it doesn't work if the image is loaded from asset bundle

var styles = StyleSheet.create({
  bgImage: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'stretch',
    resizeMode: 'stretch',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  }
});

<Image source={require('image!background')} style={styles.bgImage}>
  <Text style={styles.welcome}>
    Welcome to React Native!
  </Text>
</Image>

it looks like this:

enter image description here

however, it works fine for a remote image, through source={{uri: 'background-image-uri'}}:

enter image description here

like image 639
xinthink Avatar asked May 16 '15 08:05

xinthink


3 Answers

From Github issue: Image {require} is broken in React Native for Resizing, you could try <Image style={{width: null, height: null}}, hope that facebook would fix it soon.

like image 105
Dickeylth Avatar answered Nov 09 '22 23:11

Dickeylth


The Image tag should generally not be treated as a container view.

Having an absolutely positioned wrapper containing your (stretched/contained) image appears to work well:

var styles = StyleSheet.create({
    bgImageWrapper: {
        position: 'absolute',
        top: 0, bottom: 0, left: 0, right: 0
    },
    bgImage: {
        flex: 1,
        resizeMode: "stretch"
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10
    }
});



<View style={{ flex: 1 }}>
  <View style={styles.bgImageWrapper}>
    <Image source={require('image!background')} style={styles.bgImage} />
  </View>
  <Text style={styles.welcome}>
    Welcome to React Native!
  </Text>
</View>
like image 41
Jack Avatar answered Nov 10 '22 01:11

Jack


You could always use the Dimensions module to get the width of the screen and set your image's width style to that value:

var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');

It also seems strange that a remote image works fine...you can try loading up a local static image with the uri syntax by using source={{uri: 'local_image_file_name' isStatic: true}}.

like image 31
Dave Sibiski Avatar answered Nov 10 '22 01:11

Dave Sibiski