Thursday, March 23, 2017

Cache Images and Handle a Byte Array in the Xamarin Forms ListView

Article Url: https://visualstudiomagazine.com/articles/2017/03/01/xamarinforms-ios-android-mobile-visual-studio.aspx

I’ve always been concerned when working with images. I'm always careful with how my applications use them, as images can be relatively large and apps will typically download them via a cellular or slow Wi-Fi connection. So you might not be so concerned with image size when it takes only a few hundred milliseconds to download, but those milliseconds can add up when your app is trying to download a large number of them.

In a number of previous columns, I’ve focused on how to make a Xamarin Forms (XF) application look and act more like a native application. I'll continue along and this time I’ll look at how you can use the Xamarin.Forms ListView to cache images so that you can use the images in other locations in your application with application performance in mind.

Xamarin.Forms ListView is the equivalent of the UITableView in iOS and the ListView in Android. It allows you to present a simple grid of data to the user. The user is able to easily scroll through the data, and binding textual data to it is also a snap.

One of the problems that I see with XF ListView is that there has only been one way to easily bind the image in an ImageCell in a ListView, and that's by passing the URL of the image to the cell. ListView is then responsible for downloading the contents of the URL, handling the contents of the download, formatting the image contents and displaying the image.

The problem is that I would like to download the bytes of an image once, to a cache, and then have the cached bytes available whenever the application needs them. For example, the golf application I've been developing along with this article series displays a list of team pictures. I would like it to be able to touch the cell, have another screen open and display the image without going to the server to get it. To do this, I need to be able to cache the images. Because the application will cache the image content as a byte array, the application will need to convert from a byte array to an image, so there will need to be a Xamarin.Forms image converter to handle the binding.

I hope you enjoy the article.

No comments: