问题描述
我有一个水平 ScrollView 组件在 React Native 中包裹整个屏幕,它的第一个子元素是占据整个设备高度的图像,并延伸超过设备宽度。我试图在背景图像中绝对定位元素,以便它们在不同设备上始终处于与背景相同的相对位置,但我不知道如何。任何帮助将不胜感激。
当前代码示例:
<View style={styles.container}>
<ScrollView horizontal={true} bounces={false}>
<imagebackground style={styles.backgroundImage}>
<Element style={{position: "absolute",top: "30%",left: "50%"}}>
</imagebackground>
</ScrollView>
</View>
const styles = StyleSheet.create({
container: {
flex: 1,height: SCREEN.height,},backgroundImage: {
height: SCREEN.height,width: SCREEN.height * 1.125,})
问题是具有绝对定位的元素在不同设备上与背景图像的不同位置结束。可以解决这个问题吗?
解决方法
问题在于 <ImageBackground />
类。根据 React-Native 文档,图像适合整个可用空间,而不会丢失原始图像的宽高比,这会导致图像缩放,在这种情况下,开发人员可以控制缩放因子。
<Element style={{position: "absolute",top: "30%",left: "50%"}}>
对于上述 Element 类,您只能在使用 % 和 position: absolute
时将其定位在屏幕的宽度和高度上。
总而言之,您的 Elements 类样式代码非常完美,问题在于 <ImageBackground />
类。
而且所有设备都有不同的纵横比,因此使用这个:
width: SCREEN.height * 1.125,
可能不是最好的选择。
你可以这样做:
import {View,ScrollView,Dimension} from react-native;
const {width: viewportWidth,height: viewportHeight} = Dimensions.get('window');
<View style={styles.container}>
<ScrollView horizontal={true} bounces={false}>
<ImageBackground style={styles.backgroundImage}>
<Element style={{position: "absolute",left: "50%"}}>
</ImageBackground>
</ScrollView>
</View>
const styles = StyleSheet.create({
container: {
flex: 1,},backgroundImage: {
height: viewportHeight,width: viewportWidth,})
我希望这就是你要找的。干杯伙计!