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

问题描述:

我想在我的反应本机应用程序中使用背景图像, 图像比屏幕小,所以我必须对其进行拉伸。如何在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> 

它看起来像这样:

enter image description here

但是,它工作正常进行远程图像,通过source={{uri: 'background-image-uri'}}

enter image description here

+0

试试'resizeMode:'cover''?参考:[http://*.com/questions/29322973/whats-the-best-way-to-add-a-full-screen-background-image-in-react-native](http://*flow.com .com/questions/29322973/whats-the-best-way-to-add-a-full-screen-background-image-in-react-native) – ddaaggeett

从Github问题:Image {require} is broken in React Native for Resizing,你可以尝试<Image style={{width: null, height: null}},希望Facebook将尽快解决它。

+2

设置为我工作的宽度和高度...背景:{ flex:1, width:null, height:null, resizeMode:'stretch' }, – pkbyron

图像标记通常不应被视为容器视图。

具有包含您的(拉伸/载)图像的绝对定位的包装看起来运行良好:

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> 
+5

不幸的是,它不适合我。为什么'图像'不应该被视为一个容器,而官方文件建议[背景图像通过嵌套](https://facebook.github.io/react-native/docs/image.html#background-image-via -nesting)? – xinthink

你总是可以使用Dimensions模块来获取屏幕的宽度和图像的宽度样式设置为该值:

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

它也似乎很奇怪,一个远程图像正常工作......你可以尝试用uri SYNT加载了一个局部静态图像通过使用source={{uri: 'local_image_file_name' isStatic: true}}

+1

谢谢@dave,我认为[官方文档](https://facebook.github.io/react-native/docs/image.html#why-not-automatically-size-everything)解释它,'require('图像!x')'产生具有固定宽度和高度(图像大小)的对象:'{“__packager_asset”:true,“isStatic”:true,“path”:“...”,“uri”: “标志”, “宽度”:591, “高度”:573}'。我会尝试'uri'形式并让你知道结果,thx! – xinthink