Xamarin.Forms API - luberda-molinet/FFImageLoading GitHub Wiki

FFImageLoading for Forms provides CachedImage - a direct Image class replacement. It’s used just the same but it has some additional properties.

Step 1

Add the following NuGet packages to every project in your solution.

  • Xamarin.FFImageLoading

  • Xamarin.FFImageLoading.Forms

  • Xamarin.FFImageLoading.Transformations (if you’ll use transformations like CircleTransformation)

  • Xamarin.FFImageLoading.Svg (for SVG support)

  • Xamarin.FFImageLoading.Svg.Forms (for SVG support)

  • SkiaSharp (for SVG support)

Step 2 (Important)

You must add this line to your platform specific project (AppDelegate.cs, MainActivity.cs, Mainpage.xaml.cs, etc) before you use FFImageLoading:

if you’re using iOS or UWP:

FFImageLoading.Forms.Platform.CachedImageRenderer.Init();           

or if you’re using Android:

FFImageLoading.Forms.Platform.CachedImageRenderer.Init(enableFastRenderer: [true]/[false]);           

IImageViewHandler / IImageSourceHandler

You can now easily use FFImageLoading with standard views like Xamarin.Forms.Image. Just call this after Xamarin.Forms.Init call:

  • CachedImageRenderer.InitImageViewHandler() on Android

  • CachedImageRenderer.InitImageSourceHandler() on iOS / Mac and others

Windows UWP - Compile with .NET Native tool chain note

If your UWP app is referencing multiple assemblies (for example third party control libraries, or your application itself is split into multiple PCLs), Xamarin.Forms may be unable to load objects from those assemblies (such as custom renderers). This might occur when using the Compile with .NET Native tool chain which is an option for UWP apps in the Properties > Build > General window for the project. You can fix this by using a UWP-specific overload of the Forms.Init call in App.xaml.cs as shown in the code below:

using System.Reflection;
...
var assembliesToInclude = new List<Assembly>
{
    typeof(CachedImage).GetTypeInfo().Assembly,
    typeof(FFImageLoading.Forms.Platform.CachedImageRenderer).GetTypeInfo().Assembly            
};

Xamarin.Forms.Forms.Init(e, assembliesToInclude);

Basic Example

C#

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

XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
	x:Class="FFImageLoading.Forms.Sample.Pages.XamlSimpleExamplePage"
	xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
    Title="Basic XAML Example">
	<ContentPage.Content>
		<ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
			WidthRequest="300" HeightRequest="300"
			DownsampleToViewSize="true"
			Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg">
		</ffimageloading:CachedImage>
	</ContentPage.Content>
</PFContentPage>

Demo

Properties

Image Sources properties

Source

ImageSource property. It supports UriImageSource, FileImageSource and StreamImageSource.

LoadingPlaceholder

ImageSource property. If set, a loading placeholder is shown while loading. It supports UriImageSource, FileImageSource and StreamImageSource.

ErrorPlaceholder

ImageSource property. If set, if error occurs while loading image, an error placeholder is shown. It supports UriImageSource, FileImageSource and StreamImageSource.

Image downloading properties

RetryCount (int, default: 3)

If image download failed, or something wrong happened, it can be automatically retried. Defines retries count.

RetryDelay (int, default: 250)

If image download failed, or something wrong happened, it can be automatically retried. Defines retry delay.

CacheDuration (Timespan `, default: `TimeSpan.FromDays(90))

Defines how long file cache of downloaded image is valid.

Downsampling properties

DownSample always maintain original image aspect ratio. If you set both DownsampleWidth and DownsampleHeight, one of them is ignored.

DownsampleWidth (int, default: 0)

Resizes image to defined width in pixels (or DIP if DownsampleUseDipUnits property is set to true. If you set this property don’t set DownsampleHeight as aspect ratio will be maintained.

DownsampleHeight (int, default: 0)

Resizes image to defined height in pixels (or DIP if DownsampleUseDipUnits property is set to true. If you set this property don’t set `DownsampleWidth ` as aspect ratio will be maintained.

DownsampleUseDipUnits (bool, default: false)

If set to true, DownsampleWidth and DownsampleHeight properties will use DIP units (device independent points).

DownsampleToViewSize (bool, default: false)

If set to true image will resize to an image view size.

Transformations properties

Transformations (List<ITransformation>, default: null)

Images can be transformed when loading (original files won’t be modified). To use predefined transformations, just add FFImageLoading.Transformations package to your projects.

Example:

This transformation will transform source image to grayscale, circle-cropped image
var cachedImage = new CachedImage() {
	HorizontalOptions = LayoutOptions.FillAndExpand,
	VerticalOptions = LayoutOptions.FillAndExpand,
	DownsampleToViewSize = true,
	LoadingPlaceholder = "loading.png",
	ErrorPlaceholder = "error.png",
	Transformations = new System.Collections.Generic.List<ITransformation>() {
		new GrayscaleTransformation(),
		new CircleTransformation(),
	},
	Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg"
};
This transformation will transform source image to grayscale
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
	x:Class="FFImageLoading.Forms.Sample.Pages.XamlSimpleExamplePage"
	xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
	xmlns:fftransformations="clr-namespace:FFImageLoading.Transformations;assembly=FFImageLoading.Transformations"
    Title="Basic XAML Example">
	<ContentPage.Content>
		<ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
			WidthRequest="300" HeightRequest="300"
			DownsampleToViewSize="true"
			Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg">
			<ffimageloading:CachedImage.Transformations>
				<fftransformations:GrayscaleTransformation />
			</ffimageloading:CachedImage.Transformations>
		</ffimageloading:CachedImage>
	</ContentPage.Content>
</ContentPage>

If you use XAML-only, the linker can remove transformations. Please refer to this to resolve it: https://github.com/luberda-molinet/FFImageLoading/issues/245

TransformPlaceholders (bool?, default: null)'

Indicates if transforms should be applied to placeholders. By default this value comes from ImageService.Instance.Config.TransformPlaceholders

Other properties

BitmapOptimizations (bool?, default: null)

On Android transparency is disabled by default. This feature is not yet implemented on iOS or Windows Phone. Transparency causes images to consume twice more memory. With this property you can enable transparency for a view. Please note: Some transformations force transparency (like CircleTransformation) even when this option is disabled.

FadeAnimationEnabled (bool?, default: null)

Sets if fade animation on image loading should be enabled or disabled.

CacheKeyFactory

Gets or sets the cache custom key factory. More here: [Custom cache keys](https://github.com/molinch/FFImageLoading/wiki/Xamarin.Forms-Advanced#custom-cache-keys)

Methods

Instance methods

Cancel()

Cancels image loading.

GetImageAsJpgAsync(int quality = 90, int desiredWidth = 0, int desiredHeight = 0)

Gets the currently visible image as JPG byte array.

GetImageAsPngAsync(int desiredWidth = 0, int desiredHeight = 0)

Gets the currently visible image as PNG byte array.

Clear cache

Single item

For a single item some static methods exists directly on CachedImage.

Using name (string)

CachedImage.InvalidateCache(string key, Cache.CacheType cacheType, bool removeSimilar = false)
Clears the cache for a specified entry (Memory, Disk, All). Could be an url or filename / file path. If removeSimilar is set to true then it also removes all image cache variants ## Using an ImageSource
CachedImage.InvalidateCache(ImageSource source, Cache.CacheType cacheType, bool removeSimilar = false)
Same but with an ImageSource.

Multiple items

For multiple items please read ImageService section: https://github.com/luberda-molinet/FFImageLoading/wiki/Advanced-Usage#clear-cache

Events

Note by default callbacks are executed on background thread, you can change it with a custom config:

var config = new FFImageLoading.Config.Configuration()
{
    ExecuteCallbacksOnUIThread = true
};
ImageService.Instance.Initialize(config);

Success

Occurs after every image loading success. Returns: original ImageSize, LoadingResult

Error

Occurs after every image loading error. Returns: Exception

Finish

Occurs after every image loading. Returns: IScheduledWork

⚠️ **GitHub.com Fallback** ⚠️