我有一张从 URL 中下拉的图片。我提前不知道这张图片的尺寸。
如何对图像进行样式/布局,使其成为父视图的全宽并计算高度以保持纵横比?
我尝试在 0.34.0-rc.0 中使用 onLoad
并且高度/宽度在 event.nativeEvent.source
中均为 0。
该图像位于 <ScrollView/>
中。我不追求全屏图像。
原文由 Alex Curtis 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一张从 URL 中下拉的图片。我提前不知道这张图片的尺寸。
如何对图像进行样式/布局,使其成为父视图的全宽并计算高度以保持纵横比?
我尝试在 0.34.0-rc.0 中使用 onLoad
并且高度/宽度在 event.nativeEvent.source
中均为 0。
该图像位于 <ScrollView/>
中。我不追求全屏图像。
原文由 Alex Curtis 发布,翻译遵循 CC BY-SA 4.0 许可协议
我的使用非常相似,因为我需要以 全屏宽度 显示图像,但要 保持其纵横比。
基于@JasonGaare’s answer to use Image.getSize()
,我想出了以下实现:
class PostItem extends React.Component {
state = {
imgWidth: 0,
imgHeight: 0,
}
componentDidMount() {
Image.getSize(this.props.imageUrl, (width, height) => {
// calculate image width and height
const screenWidth = Dimensions.get('window').width
const scaleFactor = width / screenWidth
const imageHeight = height / scaleFactor
this.setState({imgWidth: screenWidth, imgHeight: imageHeight})
})
}
render() {
const {imgWidth, imgHeight} = this.state
return (
<View>
<Image
style={{width: imgWidth, height: imgHeight}}
source={{uri: this.props.imageUrl}}
/>
<Text style={styles.title}>
{this.props.description}
</Text>
</View>
)
}
}
原文由 nburk 发布,翻译遵循 CC BY-SA 3.0 许可协议
3 回答2.3k 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
1 回答808 阅读✓ 已解决
1 回答771 阅读✓ 已解决
1 回答832 阅读
1 回答1k 阅读
1 回答901 阅读
React Native 有一个内置函数,可以返回图像的宽度和高度:
Image.getSize()
。 在此处查看文档