Image组件必须要设置宽高才能显示。所以在图片宽高不确定的情况下,如何来让图片自适应屏幕高度呢?

需求原因:因为做商城详情页面的图片长短不一,所以要自适应图片显示高度。这个需求就产生了。

首先引入设备宽度

`const { width: screenWidth, height: screenHeight } = Dimensions.get('window');`

网络路径:

    Image.getSize(imageUri,(width,height) => {
    //width 图片的宽度
    //height 图片的高度
    let myHeight = Math.floor(screenWidth/width*height);
                 4 /2  * 1  = 2
    }

本地路径:

`let imageObj = Image.resolveAssetSource(state.params.cover)`
`let myHeight = Math.floor(screenWidth / width * height);`

例子:

import React, { Component } from "react";
import { StyleSheet, Image, SafeAreaView, ScrollView, ActivityIndicator, Dimensions } from "react-native";

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

class PosterDetail extends Component {
  static navigationOptions = ({ navigation }) => ({
    title:null
  });
  constructor(props) {
    super(props);
    this.state = {
      cover: '',  
      imgObjHg: 0
    }
  }
  componentDidMount() {
    let { state } = this.props.navigation
    let imageObj = Image.resolveAssetSource(state.params.cover)
    let { width, height } = imageObj
    let myHeight = Math.floor(screenWidth / width * height);
    console.log(myHeight)
    this.setState({
      cover: state.params.cover,
      imgObjHg: myHeight
    })
  }

  render() {
    return (<SafeAreaView style={{ flex: 1, backgroundColor: '#fff' }} >
      <ScrollView style={{ flex: 1, backgroundColor: '#ccc' }}>
        {this.state.cover ? <Image
          source={this.state.cover}
          style={{ width: '100%', height: this.state.imgObjHg }}
          resizeMode='center'
        /> : null}
      </ScrollView>
    </SafeAreaView>
    );
  }
}

xu57829812
28 声望0 粉丝

当我回首往事的时候,我希望我能说一句,我这一辈子我尽力了。