I’m sure there’s a lot out there on this already but one of the things that I encountered in making this little application was the need to know when an image loaded from the network is actually ready to display in Silverlight.
In that application, I have 2 images on the screen. What happens is something like this. Assume I have 2 images loaded in the app;
Get the URL of the next image we’re going to display from FlickR
Change the back image be displaying that new image by setting its URL.
Run our “spin effect” animation to spin the back image to the front image.
It’s something like that, anyway.
Now, when I was first doing this I hit a problem. It wasn’t one that surprised me as I’ve seen it before and kind of expect it anyway.
If I just do what I described then (because Silverlight loads the image from the URL asynchronously) I can get into a situation where I’m running my “spin effect” but the back image hasn’t yet loaded so I’m transitioning to a bunch of whited-out rectangles.
That’s not good 🙂
I need to be sure that when I switch one image to another then that previous image has to be 100% ready to display on the screen, no loading required, all done and dusted. I can’t swap to the next image if it’s not ready.
Simple enough. I thought I’d use WebClient and download the bits of the next image myself.
However, that didn’t work. The problem that I encountered with that was that I found that the FlickR API site seems to have a cross domain file (for Flash) and so Silverlight could read that and would allow the cross domain calls to FlickR.
However, as far as I could tell, the FlickR images seemed to be served up from some other domain which wasn’t returning a cross domain policy file. Now…it’s possible that I was doing something wrong here with FlickR as I’m a long way from being much of a power-user over there but that’s how it seemed to be.
Anyway, I accepted that using WebClient wasn’t going to work for me and decided that, because Silverlight Image is capable of loading an image from anywhere without worrying about cross domain I’d be better relying on Image to do the work. Luckily, Silverlight 3’s Image has an ImageOpened event on it which fires at the right time so I could use that event to know when my Image really is loaded and ready to stick onto the screen so I just hooked into that and use that to know when I can display the next image.