在 React Native 中保持全宽图像的纵横比

新手上路,请多包涵

我有一个关于标签的查询。我希望图像采用 alignSelf:stretch 的整个宽度,但我也希望高度根据图像的纵横比。我怎样才能实现这样的目标?

所以我想要一种方法将高度指定为图像宽度的比率。

原文由 Param Aggarwal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 595
2 个回答

对于宽高比为 3:2 的水平图像,请使用 style={{ aspectRatio: 3/2 }}

文档: https ://reactnative.dev/docs/layout-props#aspectratio

(适用于 RN 0.40+)

原文由 Param Aggarwal 发布,翻译遵循 CC BY-SA 4.0 许可协议

我喜欢 bdv 的方法,并且在我的应用程序中几乎所有地方都使用这种图像。这就是为什么我创建了一个自己的组件,它使用 onLayout 来支持设备旋转。

 import resolveAssetSource from "resolveAssetSource";
import React, { useCallback, useState } from "react";
import { Image, View } from "react-native";

export default function FullWidthImage(props) {
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);

  const onLayout = useCallback((event) => {
    const containerWidth = event.nativeEvent.layout.width;

    if (props.ratio) {
      setWidth(containerWidth);
      setHeight(containerWidth * props.ratio);
    } else if (typeof props.source === "number") {
      const source = resolveAssetSource(props.source);

      setWidth(containerWidth);
      setHeight(containerWidth * source.height / source.width);
    } else if (typeof props.source === "object") {
      Image.getSize(props.source.uri, (w, h) => {
        setWidth(containerWidth);
        setHeight(containerWidth * h / w);
      });
    }
  }, [props.ratio, props.source]);

  return (
    <View onLayout={onLayout}>
      <Image
        source={props.source}
        style={{ width, height }} />
    </View>
  );
}

你可以像这样使用它:

 <FullWidthImage source={{ uri: "http://example.com/image.jpg" }} />
<FullWidthImage source={require("./images/image.jpg")} />

或者,如果您知道这样的比率:

 <FullWidthImage source={{ uri: "http://example.com/image.jpg"}} ratio={0.5} />
<FullWidthImage source={require("./images/image.jpg")} ratio={0.5} />

原文由 tomatentobi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题