react-native

React Native Retrieve Actual Image Sizes


I would like to be able to know the actual size of a network-loaded image that has been passed into <Image /> I have tried using onLayout to work out the size (as taken from here https://github.com/facebook/react-native/issues/858) but that seems to return the sanitised size after it's already been pushed through the layout engine.

I tried looking into onLoadStart, onLoad, onLoadEnd, onProgress to see if there was any other information available but cannot seem to get any of these to fire. I have declared them as follows:

      onImageLoadStart: function(e){
        console.log("onImageLoadStart");
      },
    
      onImageLoad: function(e){
        console.log("onImageLoad");
      },
    
      onImageLoadEnd: function(e){
        console.log("onImageLoadEnd");
      },
    
    
      onImageProgress: function(e){
        console.log("onImageProgress");
      },
    
      onImageError: function(e){
        console.log("onImageError");
      },
    
      render: function (e) {
        return (
          <Image
            source={{uri: "http://adomain.com/myimageurl.jpg"}}
            style={[this.props.style, this.state.style]}
            onLayout={this.onImageLayout}
            onLoadStart={(e) => {this.onImageLoadStart(e)}}
            onLoad={(e) => {this.onImageLoad(e)}}
            onLoadEnd={(e) => {this.onImageLoadEnd(e)}}
            onProgress={(e) => {this.onImageProgress(e)}}
            onError={(e) => {this.onImageError(e)}} />
        );
      }

Thanks.


Solution

  • Image component now provides a static method to get the size of the image. For example:

    Image.getSize(myUri, (width, height) => {this.setState({width, height})});