我有一个关于标签的查询。我希望图像采用 alignSelf:stretch 的整个宽度,但我也希望高度根据图像的纵横比。我怎样才能实现这样的目标?
所以我想要一种方法将高度指定为图像宽度的比率。
原文由 Param Aggarwal 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个关于标签的查询。我希望图像采用 alignSelf:stretch 的整个宽度,但我也希望高度根据图像的纵横比。我怎样才能实现这样的目标?
所以我想要一种方法将高度指定为图像宽度的比率。
原文由 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 许可协议
3 回答2.3k 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
1 回答816 阅读✓ 已解决
1 回答781 阅读✓ 已解决
1 回答839 阅读
1 回答1k 阅读
1 回答914 阅读
对于宽高比为 3:2 的水平图像,请使用
style={{ aspectRatio: 3/2 }}
。文档: https ://reactnative.dev/docs/layout-props#aspectratio
(适用于 RN 0.40+)