我在我的 React Native 应用程序中使用
ImageBackground
,但它没有覆盖 View
的整个高度
你可以看到有红色空间没有被我的图像覆盖。
下面是我的代码:
<View
style={styles.subDomainItem}>
<ImageBackground
resizeMode={'cover'}
source={ImageConfig.script_default_cloud}
style={{
width: '100%',
height: (dimensions.width - 20) / 2,
backgroundColor: 'red',
flex: 1,
justifyContent: 'center',
}}></ImageBackground>
</View>
subDomainItem: {
maxWidth: '94%',
width: '94%',
marginHorizontal: '3%',
marginVertical: 10,
overflow: 'hidden',
borderRadius: 10,
flex: 1,
elevation: 8,
},
我希望我的图像覆盖顶部和底部的所有红色空间,但我不知道我做错了什么。
试试这个。工作正常
import React from 'react'
import { View, ImageBackground,Text, Dimensions } from 'react-native'
const Backimage = () => {
return(
<ImageBackground
style={{width:Dimensions.get("screen").width, height:Dimensions.get("screen").height}}
source={require("./src/assets/water.png")} resizeMethod="resize">
</ImageBackground>
)
}
export default Backimage
我认为你应该在设置 subDomainItem 视图的样式时给它一个明确的高度。您指定了 94% 的宽度,但没有指定高度。
如果父组件(本例中为 subDomainItem)具有明确的高度,则 ImageBackground 应该可以正常工作,将其高度设置为 100%。
如果你想覆盖父视图的所有空间,你不想给 ImageBackground 提供高度和宽度,你只需要为 ImageBackground 提供 flex: 1 或高度和宽度为 100%。
import {
View,
Text,
ImageBackground,
Dimensions,
StyleSheet,
} from 'react-native';
const WIDTH = Dimensions.get('screen').width;
const HEIGHT = Dimensions.get('screen').height;
const MainPage = () => {
return (
<View style={styles.subDomainItem}>
<ImageBackground
resizeMode="contain"
source={ImageConfig.script_default_cloud}
style={styles.bgImageStyle}
>
<Text>Sample</Text>
</ImageBackground>
</View>
);
};
const styles = StyleSheet.create({
subDomainItem: {
width: WIDTH,
height: HEIGHT,
alignItems: 'center',
},
bgImageStyle: {
justifyContent: 'center',
resizeMode: 'contain',
width: WIDTH,
height: HEIGHT,
}
})
如果状态栏的样式是自动,那么您需要将该高度添加到尺寸中,以便您可以获得任何屏幕尺寸的屏幕高度
从 'react-native' 导入 { Dimensions, StatusBar }
const HEIGHT = Dimensions.get("window").height + StatusBar.currentHeight;
然后在程序中使用它就像