我希望我的图像尽可能适合它的父级,同时保持其宽度/高度比。我在运行时获取图像,所以我事先不知道图像的宽度/高度,所以它需要是动态的。
在网络中,我可以通过以下方式实现:
.image {
width: 100%;
height: 100%;
object-fit: contain;
}
它应该是这样的(简化):
https://codepen.io/laurentsmohr/pen/OBEGRG?fbclid=IwAR1-dFcTC7vvXwd0m2NTeCMxm6A6Uzv0lFx2UUCNpgFnpSgEm9aHhr14LK4
最佳答案
根据 this official React-Native guide ,如果你想根据其父元素的尺寸动态缩放图像,你必须将图像的宽度和高度设置为未定义,并且可能还要在图像 Prop 中添加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;
关于react-native - 使图像填充父级,但在 react 原生(动态/网络图像)中保持比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52914337/