Skip to content

Xamarin.Forms Advanced

Daniel Luberda edited this page Jan 7, 2016 · 32 revisions

Usage in ListView with ListViewCachingStrategy.RecycleElement enabled

If you use CachedImage views inside ViewCells of a ListView with ListViewCachingStrategy.RecycleElement enabled, instead using bindings for setting Source property - please use ViewCell's OnBindingContextChanged override to update it to avoid loading images to wrong views.

ImageService.Initialize() method

You can override CachedImage global defaults by calling ImageService.Initialize method in platform specific project. You can globally enable transparency channel, disable fade animation, specify own logger, timeouts and a lot more. Read more details here: link

Custom cache keys

You can force FFImageLoading to use custom keys for cache. For that you need to make your own ICacheKeyFactory implementation and set CachedImage.CacheKeyFactory property to it.

Custom cache key Example:

class CustomCacheKeyFactory : ICacheKeyFactory
{
	public string GetKey(ImageSource imageSource, object bindingContext)
	{
		if (imageSource == null)
			return null;

		string itemSuffix = string.Empty;
		var bindingItem = bindingContext as ListExampleItem;

		if (bindingItem != null)
			itemSuffix = bindingItem.FileName;

		// UriImageSource
		var uriImageSource = imageSource as UriImageSource;
		if (uriImageSource != null)
			return string.Format("{0}+myCustomUriSuffix+{1}", uriImageSource.Uri, itemSuffix);

		// FileImageSource
		var fileImageSource = imageSource as FileImageSource;
		if (fileImageSource != null)
			return string.Format("{0}+myCustomFileSuffix+{1}", fileImageSource.File, itemSuffix);

		// StreamImageSource
		var streamImageSource = imageSource as StreamImageSource;
		if (streamImageSource != null)
			return string.Format("{0}+myCustomStreamSuffix+{1}", streamImageSource.Stream.GetHashCode(), itemSuffix);

		throw new NotImplementedException("ImageSource type not supported");
	}
}

Custom cache key factory C# usage

var cachedImage = new CachedImage() {
	HorizontalOptions = LayoutOptions.Center,
	VerticalOptions = LayoutOptions.Center,
	WidthRequest = 300,
	HeightRequest = 300,
	CacheDuration = TimeSpan.FromDays(30),
	DownsampleToViewSize = true,
	RetryCount = 0,
	RetryDelay = 250,
	TransparencyEnabled = false,
	Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg",
	CacheKeyFactory = new CustomCacheKeyFactory(),
};

Custom cache key factory XAML usage

<ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
	WidthRequest="300" HeightRequest="300"
	DownsampleToViewSize="true"
	Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg">
	<ffimageloading:CachedImage.CacheKeyFactory>
		<local:CustomCacheKeyFactory/>
	</ffimageloading:CachedImage.CacheKeyFactory>
</ffimageloading:CachedImage>