View 中的 React-Native 图像大小未知大小

React-Native Image sizing in View with unknown size

React-Naive 建议开发人员在运行前声明图像尺寸。我知道这是一个很好的做法。我的问题是...如果我想将 <Image> 的大小调整为与其包含的 <View> 相同的宽度且宽度未知怎么办?

例如,我在 <View>rowDirection: 'row', flex: 0.8 中有一个 <Image>。在不同的设备中,我有不同的屏幕宽度。我如何知道设备 80% 的实际宽度?

P.S。我已经尝试了所有 resizeMode 但没有成功。

谁能帮帮我谢谢!

更新 1

我试过这个片段

<View style={{ flexDirection: 'row', flex: 1, backgroundColor: '#CCF' }}>
    <Image
        source={require('../resources/images/side-menu-header.png')}
        style={{ width: null, height: null, flex: 0.8 }} />
    <View style={{ flex: 0.2 }} />
</View>

Result image of above code

但是,是的,这张图片现在宽度设置为 0.8,但它的一些区域已被裁剪。这不是我想要得到的。因此,我将其 resizeMode 设置为 contain 如下片段

<View style={{ flexDirection: 'row', flex: 1, backgroundColor: '#CCF' }}>
    <Image
        resizeMode='contain'
        source={require('../resources/images/side-menu-header.png')}
        style={{ width: null, height: null, flex: 0.8 }} />
    <View style={{ flex: 0.2 }} />
</View>

Result image of above code

这也出乎我的意料!如您所见,图像现在宽度变为 0.8,并且显示了整个图像,但顶部和底部 space 被其原始尺寸占据。 (原图尺寸较大)

我想我可以用几句话来简化这个问题:如何在我的应用程序中显示全宽图像?我无法将其宽度设置为 1080,因为并非所有设备的宽度都是 1080 像素。

nullwidthheight 传递给 style 属性,如下所示:

<Image resizeMode='cover' source={{ uri: 'image.png' }} style={{ width: null, height: null, flex: 0.8 }} />

就我而言,您需要的是 api 来获取设备的大小。

试试 Dimensions,像这样使用:

let {height, width} = Dimensions.get('window');

使用尺寸 API 使图像大小动态化。

示例代码:

const { width, height } = Dimensions.get('window');
<Image
    source={{uri: `${url}`}}
    style={{ width: width * 0.8, height: height * 0.8 }}
/>

width * 0.8 和 height * 0.8 分别是屏幕尺寸宽度和高度的 80%。