Maintain aspect ratio of image with full width in React Native

前端 未结 12 1464
终归单人心
终归单人心 2020-12-07 13:02

I have a query regarding tag. I want an image to take entire width of parent which I do using alignSelf:stretch, but I also want the height to be according to the aspect ra

12条回答
  •  囚心锁ツ
    2020-12-07 13:43

    It's actually pretty simple.

    The Image class has a getSize method. [1]

    Let's say that you've created a component for your aspectRatioImage and you calculate the appropriate values every time componentWillMount fires.

    Then your code would look something like this:

    componentDidMount() {
        Image.getSize(this.props.source.uri, (srcWidth, srcHeight) => {
          const maxHeight = Dimensions.get('window').height; // or something else
          const maxWidth = Dimensions.get('window').width;
    
          const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
          this.setState({ width: srcWidth * ratio, height: srcHeight * ratio });
        }, error => {
          console.log('error:', error);
        });
      }
    

    So now that the image height and width are saved in your component's state, you can just run

     
    

    [1] - https://facebook.github.io/react-native/docs/image.html#getsize

提交回复
热议问题