如何在React Native中将静态图像拉伸为背景?

xin*_*ink 12 react-native

我想在我的本机应用程序中使用背景图像,图像小于屏幕,所以我必须拉伸它.

但是如果图像是从资产包中加载的,它就不起作用

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>
Run Code Online (Sandbox Code Playgroud)

它看起来像这样:

在此输入图像描述

但是,它适用于远程图像,通过source={{uri: 'background-image-uri'}}:

在此输入图像描述

Dic*_*lth 24

来自Github问题:图片{require}在React Native中用于调整大小,你可以试试<Image style={{width: null, height: null}},希望facebook能尽快修复它.

  • 设置宽度和高度为我工作... background:{flex:1,width:null,height:null,resizeMode:'stretch'}, (3认同)

Jac*_*ack 9

通常不应将Image标记视为容器视图.

拥有一个包含您的(拉伸/包含)图像的绝对定位包装似乎运行良好:

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>
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,它对我不起作用.为什么`Image`不应该被视为容器,而官方文档建议[通过嵌套的背景图像](https://facebook.github.io/react-native/docs/image.html#background-image-via -nesting)? (5认同)