如何在 React Native 中将图像宽度设置为 100% 并将高度设置为自动? [英] How to set image width to be 100% and height to be auto in react native?

查看:100
本文介绍了如何在 React Native 中将图像宽度设置为 100% 并将高度设置为自动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在滚动视图中显示图像列表.宽度应该是 100%,而高度应该是自动的,保持纵横比.

I am trying to display list of images in a scrollview. Width should be 100%, while height should be automatic, keeping aspect ratio.

我所做的搜索指向了提供全屏背景样式的各种解决方案.

The searches I did pointed to various solutions which give fullscreen background style.

const styles = StyleSheet.create({
    image: {
        width: null,
        height: 300,
        resizeMode: 'cover'
    }
});

<ScrollView style={{flex: 1}}>
    <Image style={styles.image} source={require('../../../images/collection-imag1.png')}/>
    <Image style={styles.image} source={require('../../../images/collection-imag2.png')}/>
</ScrollView>

我尝试了各种宽度的组合:null、height:null、flex:1、alignSelf 等.上面的解决方案几乎可以工作,除了高度不是动态的.部分图像不可见.

I have tried various combinations of width: null, height: null, flex: 1, alignSelf etc. The above solution is almost working, except the height is not dynamic. Parts of the image are not visible.

推荐答案

所以经过思考一段时间后,我能够实现 height: auto in react-native image.您需要知道图像的尺寸才能使此 hack 起作用.只需在任何图像查看器中打开您的图像,您就会在文件信息中获得图像的尺寸.作为参考,我使用的图像大小是 541 x 362

So after thinking for a while I was able to achieve height: auto in react-native image. You need to know the dimensions of your image for this hack to work. Just open your image in any image viewer and you will get the dimensions of the your image in file information. For reference the size of image I used is 541 x 362

首先从 react-native 导入 Dimensions

First import Dimensions from react-native

import { Dimensions } from 'react-native';

然后你必须得到窗口的尺寸

then you have to get the dimensions of the window

const win = Dimensions.get('window');

现在计算比率为

const ratio = win.width/541; //541 is actual image width

现在为您的图像添加样式

now the add style to your image as

imageStyle: {
    width: win.width,
    height: 362 * ratio, //362 is actual height of image
}

这篇关于如何在 React Native 中将图像宽度设置为 100% 并将高度设置为自动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆