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.
To get the dimensions of image with React, we can get it from the load event handler of the image. We define the onImgLoad function that gets the image from the target property. Then we destructure the offsetHeight and offsetWidth properties from the image. Next, we log the height and width with console.
Creating a function named as getImageDimensions(). In this function we would use the inbuilt Image. getSize() method with Image URL and width height. When we call this function then it would automatically calculate Image width and height and Store into States.
You can easily get the size of the View by onLayout props. The onLayout handler will also be invoked whenever the view is resized. The main caveat is that the onLayout handler is first invoked one frame after your component has mounted, so you may want to hide your UI until you have computed your layout.
To fetch image from API with React, we can use the fetch function. We call fetch with the imageUrl to make a GET request to it. Then we call res. blob to convert the response object to a blob.
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})});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With