使图像填充父级,但保持反应本机(动态/网络图像)的比例



我希望我的图像尽可能适合其父级,同时保持其宽/高比。我在运行时获取图像,所以我事先不知道图像的宽度/高度,所以它必须是动态的。

在网络中,我可以通过以下方式实现这一点:

.image {
width: 100%;
height: 100%;
object-fit: contain;
}

这是它应该的样子(简化(:
https://codepen.io/laurentsmohr/pen/OBEGRG?fbclid=IwAR1-dFcTC7vvXwd0m2NTeCMxm6A6Uzv0lFx2UUCNpgFnpSgEm9aHhr14LK4

根据这个官方的 React-Native 指南,如果你想根据它的父元素尺寸动态缩放图像,你必须将图像的宽度和高度设置为 undefined,也许还会添加 resizeMode="contain" 到图像道具中。 您可以对图像使用以下样式:

import { StyleSheet, Dimensions } from 'react-native;
// Get device width
const deviceWidth = Dimensions.get('window').width;
/*
image container dimension is dynamic depending on the device width
image will dimension will follow imageContainer's dimension
*/
const styles = StyleSheet.create({
imageContainer: {
height: deviceWidth * 0.8,
width: deviceWidth * 0.8
},
image: {
flex: 1,
height: undefined,
width: undefined
}
});
export default styles;

我总是使用StyleSheet.absoluteFillObject。它将填充父母的大小。resizeMode可以contain, cover, stretch, center, repeat.喜欢这个:

image: {
resizeMode: 'cover',
...StyleSheet.absoluteFillObject,
},

虽然上面发布的解决方案适用于本地映像,但它们不适用于网络映像。 原因如下: https://facebook.github.io/react-native/docs/images#why-not-automatically-size-everything

对我来说,最简单的解决方案是根据维度高度和组件在视图中的弯曲部分来计算组件的高度。
例如,在我看来,图像组件具有 .85 flex,在父级中具有 1 flex。 所以父母的 100% 高度等于:

Dimensions.get('window').height * 0.85

这种样式对我有用:

image: {
flex: 1,
resizeMode: "contain",
},

:发货:

React Next 为填充其父容器的图像设置:

image={
<Image
src="https://picsum.photos/1174/611?random=65411"
alt="mandatory alt text goes here"
quality={100}
layout="fill"
/>
}

最新更新