DEV Community

Enmanuel Toribio
Enmanuel Toribio

Posted on • Originally published at blog.torib.io on

Image caching in Xamarin Forms

Someone asked me about an issue they were having when showing a ListView that had an image for each cell. When the user would scroll the images would flicker and the UI would turn a bit slow. The images were being loaded from the internet.

The problem the person was having was that they were not using a correct caching strategy for the images and now I’m going to explain how you can fix this problem in case it happens to you.

Enough context, let’s do the caching

If you want to add cache to your image you should use something like this:

Some explanations ensue

When you want to show an image you know you specify the Source of the Image. Probably as a URL or a route to a resource, both look like strings but if you look a bit further you will notice the Source property of the Image is actually of type ImageSource and it can be assigned any value that inherits from it.

In the code sample, we set the Source to an instance of UriImageSource. This class has more properties but the three properties we want to focus on are:

  • Uri: This is the address of the image we want to show.
  • CachingEnabled: This is a boolean value that will Enable or Disable the caching. The default value is true.
  • CacheValidity: The timestamp when the cache will be dismissed. The timestamp parameters are Days, Hours, Minutes, Seconds. In the Code sample, we are setting the cache to 7 days. In the XAML sample to 30 days.

And that’s it. Pretty concise and quite useful. Hope you liked reading it as much as I did writing this article. You can get more information on working with images and the source for the feature image in this article from the official Xamarin Documentation. Bye!

The post Image caching in Xamarin Forms appeared first on Enmanuel Toribio.

Top comments (0)