React native 如何使用React Native调整图像大小?为什么这么复杂?
我的原始图像测量值为React native 如何使用React Native调整图像大小?为什么这么复杂?,react-native,React Native,我的原始图像测量值为1080(w)*607(h)。它来自服务器(而不是本地)。尺寸不应该是已知的(我有很多不同尺寸的图像) 我只是想让我的图像在我的设备上完全可见,这与比例有关 我尝试在resizeMode:contain中显示此图像,宽度为100%。它显示得非常好,但是有很大的空白(我添加了一个红色背景来实现这一点)。我不明白这个边际 return ( ... <Image source={{ uri: http://... }} containerS
1080
(w)*607
(h)。它来自服务器(而不是本地)。尺寸不应该是已知的(我有很多不同尺寸的图像)
我只是想让我的图像在我的设备上完全可见,这与比例有关
我尝试在resizeMode:contain
中显示此图像,宽度为100%
。它显示得非常好,但是有很大的空白(我添加了一个红色背景来实现这一点)。我不明白这个边际
return (
...
<Image
source={{ uri: http://... }}
containerStyle={[
styles.image_container
]}
resizeMode="contain"
/>
....
)
const styles = StyleSheet.create({
image_container: {
backgroundColor: 'red',
width: '100%',
aspectRatio: 1
},
)}
返回(
...
....
)
const styles=StyleSheet.create({
图像容器:{
背景颜色:“红色”,
宽度:“100%”,
方面:1
},
)}
我想这是因为方面:1
但是如果我删除aspectRatio:1
图像将被隐藏。我尝试了很多与宽度
/高度
/aspectRatio
的组合
我在谷歌上搜索了很多(很多很多),但是这个问题经常返回很多可能性(有很多计算()),并且没有普遍的答案
我认为我的处境是最简单的,但它看起来太复杂了,变得很奇怪。试试这个:
import React, { useState } from 'react'
import { View, Image, Dimensions } from 'react-native';
const [width, setWidth] = useState();
const [height, setHeight] = useState();
const win = Dimensions.get('window');
Image.getSize(myUri, (width, height) => {setWidth(width); setHeight(height)});
const a = 0.5;
const App = () => {
return(
<View>
<Image source={myUri} style={styles.image}>
</View>
)
}
const styles = Stylesheet.create({
image: {
resizeMode: 'contain',
width: a * win.width,
height: (a * win.width)*(height/width),
}
})
import React,{useState}来自“React”
从“react native”导入{View,Image,Dimensions};
const[width,setWidth]=useState();
const[height,setHeight]=useState();
const win=Dimensions.get('window');
getSize(myUri,(width,height)=>{setWidth(width);setHeight(height)});
常数a=0.5;
常量应用=()=>{
返回(
)
}
const styles=Stylesheet.create({
图片:{
resizeMode:'包含',
宽度:a*win.width,
高度:(a*win.width)*(高度/宽度),
}
})
这里我们使用屏幕的宽度来确定图像的最佳宽度。您可以改变a
的值以设置所需的宽度%<计算代码>高度以保持图像的纵横比。您可以使用
从“React”导入React;
从“react native”导入{Dimensions};
从“react native scalable Image”导入图像;
常量图像=(
);
您是否尝试过类似的计算方面?我现在不能检查,但似乎是简单和工作。“盖洛德。P请考虑奖励赏金,如果我的答案帮助你。即使你不把赏金奖励给任何人,你花在赏金上的名誉也不会回来。为什么不仅仅是一个常量宽度%和一个计算的aspectRatio
?@DávidLaczkó,这取决于用户。我编写的代码提供了更改宽度%的灵活性,但对于具体问题,它似乎有点过于复杂。OP提出的一个简单的解决方案可能是我在问题下面链接的一个。
yarn add react-native-scalable-image
import React from 'react';
import { Dimensions } from 'react-native';
import Image from 'react-native-scalable-image';
const image = (
<Image
width={Dimensions.get('window').width} // height will be calculated automatically
source={{uri: '<image uri>'}}
/>
);