包含图像比例的全宽图像未在React-Native中拉伸

时间:2018-09-17 09:41:30

标签: react-native

我正在尝试添加宽度始终为100%但高度拉伸的图像,其中包含图像的比例。

我正在将图像添加到容器中:

 <View style={styles.imageContainer}>
     <Image style={styles.image} source={require('../../assets/images/image.png')}/>
 </View>

并将调整大小模式更改为“包含”:

const styles = StyleSheet.create({
    imageContainer: {
        flex: 1,
    },

    image: {
        width: '100%',
        resizeMode: 'contain',
        backgroundColor: 'red',
    }
}

enter image description here

图像背景显示图像为100%宽度(红色背景),但源未拉伸。实现以下结果的正确方法是什么?

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试:

import {Dimensions} from 'react-native';

const deviceWidth = Dimensions.get('window').width;

.............
.............

const styles = StyleSheet.create({

    image: {
        ....
        width: deviceWidth,
        resizeMode: 'stretch',
        .....
    }
}

答案 1 :(得分:0)

您可以先导入该库:

import Dimensions from 'react-native';

然后您全局定义:

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

编写代码的正确方法是:

const styles = StyleSheet.create({
    imageContainer: {
        flex: 1,
        height: height,
    },

    image: {
        width: width,
        resizeMode: 'contain',
        backgroundColor: 'red',
    }
}