如何在React Native中强制使图像全宽并保持宽高比?
如何在React Native中强制使图像全宽并保持宽高比?
我从一个URL上下载了一个图像,但我事先不知道这个图像的尺寸。
如何设置/布局图像,使其尽可能地占满父视图的宽度,并且高度可以被计算出来,从而保持它的宽高比?
我尝试在0.34.0-rc.0中使用onLoad
,但event.nativeEvent.source
中的高度/宽度都为0。
这个图像在一个中。我不需要一个全屏图像。
admin 更改状态以发布 2023年5月24日
我的应用场景与 @JasonGaare 提供的答案类似,我需要展示一张图片,宽度全屏,但同时又要 保持其长宽比。
基于 @JasonGaare 使用 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 () } } {this.props.description}