Let's say we want to use an image from the web
and for that, you can simply pick one here, I'll do it with Google image search, let's say this one and
we want to use that image on our game over screen.
Now before, we use this require syntax to load a local image,
now this syntax will no longer be the right one.
So I'll duplicate this line and comment it out, for a web image,
instead you pass an object to source and on that object, you pass a URI prop and that URI
prop holds a string which is your link to the image.
So your link to the image is passed to the URI prop in this object which you passed to source.
Now if you do that, this loads the image from the web but there is one important thing you have to know.
For the image
that was loaded locally,
I mentioned that React Native is able to determine its width and height and uses that as a default.
Therefore for a locally loaded image, you don't have to set a width and height on the image,
we're doing it here because we want to override the default width and height
but if you had an image that is already perfectly sized, you wouldn't have to set width and height. For
images from the web,
React Native is not able to determine the width and the height of the image before it's loaded because
it's not part of the app, it's coming from a web,
React Native downloads it and it's kind of a surprise regarding what the width and the height is. Therefore
for network images,
so for images you are fetching with a link, you always have to set a width and a height on the image
object, on the image component here. For local images added with require,
you can do that as we're doing it to override it but you don't have to,
that's an important differentiation.
Now you might have also seen that for web images, the loaded image actually faded in when it was loaded
for the first time and that's a nice factory effect React Native adds automatically for network images.
It downloads that image and whilst you're waiting for the download to complete, it basically shows
nothing, it can't show the image yet but when the image is loaded, it doesn't just pop it in there but instead,
it slowly fades it in which is a nicer transition for that loaded image.
That's a nice effect and you can also control this with fade duration,
you can set this to a number and the default is 300,
that would be 300ms but you can set this to a different millisecond value, like 1000ms
which would be one second for the image to fade and so on. After the first load, the image is cached and
therefore subsequent usages of the same image happened pretty much instantly because it already was
downloaded.
So that's how to use network images and what to be aware of regarding those.