React Native - 如何在宽度 = "100%" 的情况下保持图像比例?



我的数据库中有图像uri,我正在用width: "100%"渲染它们

由于图像可以是1080x1080、750x1080和1920x1080,我需要找到一种方法来渲染它们,以保持纵横比。。。我的意思是,如果我的设备的宽度是600px,图像的宽度必须是600px("100%"(,并且它的高度必须自动调整,以避免丢失其比例。

我试过这个CSS:

image: {
width: "100%",
aspectRatio: 1,
},

但仅适用于正方形图像(1080x1080(如何在react native中执行height: "auto",以便根据其他图像的正确方向调整其大小?

重要提示:我不知道图像的尺寸,我只知道图像的宽度必须等于设备宽度。

您必须采取一些步骤。

首先,你需要知道图像的确切大小,以及你用Image.getSizeImage.getSizeWithHeaders做的事情

让我在下面举一个你可以怎么做的例子。

export interface ImageDetli {
width: number;
height: number;
url: string;
}
const ImageRenderer = ({
url
}: {
url: string
}) => {
const [windowWidth, setWindowWidth] = useState(Dimensions.get("window").width);
const [windowHeight, setWindowHeight] = useState(Dimensions.get("window").height);
const [loading, setLoading] = useState(true); // untill we load the image fully
const [image, setImage] = useState(undefined as ImageDetli | undefined)
const getSize = async(url: string) => {
return new Promise((resolve, reject) => {
// this is very imported so you can keep an eye on the size of the image
Image.getSize(url, (width, height) => {
resolve({
url: url,
width: width > windowWidth ? windowWidth : width,
height: height > windowHeight ? windowHeight : height
});
}, async(error) => {
console.log("image not loaded: " + url);
console.log(error)
resolve(undefined);
})
}) as Promise <ImageDetli | undefined>
}
useEffect(() => {
(async() => {
var imageDetali = await getSize(url);
if (!imageDetali){
// load an empty Image or somthing
}else {
setImage(imageDetali);
}
setLoading(false)
})();
}, [])

return (
<>
{loading?(<ActivityIndicator size="large"color="#0000ff"/>)
:
(
<View style={{ width: "100%", height: "100%", alignItems: "center", 
justifyContent: "center" }}>
<Image source={{uri: image.url}}
style={{ width:image.width, height image.height, resizeMode: "contain" }} />
</View>
)}
</>
)
}

我希望你能理解这一点,你可以问你是否需要了解更多。

相关内容

最新更新