如何使用 React Native 强制图像为全宽并保持纵横比?

新手上路,请多包涵

我有一张从 URL 中下拉的图片。我提前不知道这张图片的尺寸。

如何对图像进行样式/布局,使其成为父视图的全宽并计算高度以保持纵横比?

我尝试在 0.34.0-rc.0 中使用 onLoad 并且高度/宽度在 event.nativeEvent.source 中均为 0。

该图像位于 <ScrollView/> 中。我不追求全屏图像。

原文由 Alex Curtis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

React Native 有一个内置函数,可以返回图像的宽度和高度: Image.getSize()在此处查看文档

原文由 Jason Gaare 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题