Image caching in Xamarin Forms

Share on facebook
Share on twitter
Share on linkedin

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!

Did you like the post and would like to leave a reply? You can mention me on twitter @eatskolnikov so we can have a conversation about it

Share it with your friends

Share on facebook
Share on twitter
Share on linkedin

Want to get these post in your inbox?

Type your email down here and you will get a weekly digest of the post here

Other articles on the site


Handling Excel Files with NPOI

NPOI is a library for working with Office documents like Word and Excel. I mainly been using it for reading and writing Excel files so that’s what I’m going to write about. It works with .csv and .xlsx formats and is based on the Apache POI project for Java. It

Read More »