React Native ImageBackground图片横向超出屏幕被裁剪如何解决?
解决方法
核心问题为ImageBackground组件的resizeMode属于组件专属属性,不能写在style样式对象中,你注释掉的写在page样式里的resizeMode不会生效,这是适配失效的主要原因。
- 给
ImageBackground组件直接添加resizeMode="contain"属性,不要写在样式内 - 若仍有适配问题,可以搭配
imageStyle属性调整内部承载图片的样式,例如设置宽高为100%
修改后的完整代码如下:
import React from 'react'; import { Image, ImageBackground, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import {DCTBACKGROUND} from '../../../assets/images'; export default function GetStarted({navigation}) { return ( <ImageBackground source={DCTBACKGROUND} style={styles.page} resizeMode="contain" // 可选:调整内部图片样式 imageStyle={{width: '100%', height: '100%'}} > <View style={styles.buttonContainer}> <TouchableOpacity style={styles.button} onPress={() => { navigation.navigate('Register'); }}> <Text style={styles.buttonText}>Registrasi</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={() => { navigation.navigate('Login'); }}> <Text style={styles.buttonText}>Login</Text> </TouchableOpacity> </View> </ImageBackground> ); } const styles = StyleSheet.create({ page: { backgroundColor: '#90CC8B', flex: 1, paddingHorizontal: 15, paddingVertical: 25, }, button: { backgroundColor: 'yellow', width: 100, height: 40, alignItems: 'center', justifyContent: 'center', borderWidth: 1, }, buttonText: { color: 'black', }, buttonContainer: { justifyContent: 'space-between', flexDirection: 'row', }, logo: { alignItems: 'center', justifyContent: 'center', flex: 1, }, });
Image组件的resizeMode支持写在样式中,而ImageBackground的style仅作用于外层包裹的View组件,内部承载图片的Image元素的属性需要通过组件根属性或者imageStyle单独设置。如果需要图片拉伸铺满屏幕可以选择resizeMode="stretch",如果要保持图片比例完整显示选择contain即可。
内容的提问来源于stack exchange,提问作者Dragonarc
相关产品推荐
相关产品推荐

