使图像填充父级,但在反应原生(动态/网络图像)中保持比例

Lau*_*ohr 4 mobile frontend react-native

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

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

.image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
Run Code Online (Sandbox Code Playgroud)

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

小智 7

根据这个官方的 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;
Run Code Online (Sandbox Code Playgroud)

  • 这可能适用于静态图像,但不适用于动态图像。 (2认同)

Lau*_*ohr 0

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

对我来说最简单的解决方案是根据组件在视图中的尺寸高度和弯曲部分来计算组件的高度。
例如,在我看来,图像组件的弯曲度为 0.85,而父级组件的弯曲度为 1。所以父级的 100% 高度等于:

Dimensions.get('window').height * 0.85
Run Code Online (Sandbox Code Playgroud)