Search code examples
cachingmemoryxamarin.formsimage-caching

Xamarin.Forms Image Caching Cross-Platform Solution


We have number of images used as app assets, for case of simplicity, let's say 10 images only.

As far as I understand, Xamarin.Forms will not cashe these images, so if I have these 10 images showing in my toolbar (this is just to explain issue, we would not really put 10 images in a tiny toolbar) and I have 5 pages showing same toolbar, that means the 10 images will be loaded each 5 times resulting in total 50 images loaded. I would like to load only 10 images rather than loading 5pages x 10images = 50 images.

In addition, if I have to add these 10 images in our repository, I would have to add at least 3 copies of same image to our repository (1 for Android, 1 for IOS, 1 for UWP). This results in 30 images in repository but in reality I needed only 10.

So, these 2 issues make be believe there should be a better cross-platform solution so I can share same image across all 3 platforms, have only one image used by all 3 platforms (Android, IOS, UWP), and I load an image only once in memory regardless how many times I show in the UI.


Solution

  • You can look into FFImageLoading which supports caching. To have images in your shared code instead of your platform-specific code you could look into embedded images:

    Embedded images are also shipped with an application (like local images) but instead of having a copy of the image in each application's file structure the image file is embedded in the assembly as a resource. This method of distributing images is particularly suited to creating components, as the image is bundled with the code.

    https://developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Embedded_Images

    Keep in mind though that adding images per platform isn't a bad thing. Each platform has its own image versions due to different pixel densities etc. so to make it look good on each platform you might want to consider the platform-specific route.

    Another alternative is adding your images as file-linked images in each platform specific file. The image file itself can saved in a single location and file-linked into the correct directories per platform.