XAML Image Cheatsheet

by Giang, last updated 19 Jan 2018

This is a cheatsheet for embedding images in Xamarin Forms, summary of Images - Xamarin Forms Documentation

Three ways to embed images:

  • Local images - displaying images shipped with the application
  • Embedded images - displaying images embedded as an assembly resource
  • Remote images - displaying images from Internet

Embed Local Images

XAML only:

<Image Source="waterfront.jpg" />

Using code behind:

image.Source = "waterfront.jpg";

Using this method, same image file name must be available on each platform, adhere to platform rule about naming convention and file path.

For more flexibility:

image.Source = Device.OnPlatform(
    iOS: ImageSource.FromFile("Images/waterfront.jpg"),
    Android:  ImageSource.FromFile("waterfront.jpg"),
    WinPhone: ImageSource.FromFile("Images/waterfront.png"));

Embed Images from Resources

By default, we need help from code behind to set image source to resource:

<Image x:Name="image" />
// using resource
image.Source = ImageSource.FromResource("WorkingWithImages.beach.jpg");

XAML-only solution

Add an extension for XAML

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Foobar.Helpers
{
    [ContentProperty("Source")]
    public class ImageResourceExtension : IMarkupExtension
    {
        public string Source { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Source == null)
                return null;

            // Do your translation lookup here, using whatever method you require
            var imageSource = ImageSource.FromResource(Source);

            return imageSource;
        }
    }
}

Include the extension in page that embeds images:

xmlns:local="clr-namespace:Foobar.Helpers;assembly=Foobar"

And finally:

<Image Source="{local:ImageResource Foobar.Resources.CompanyLogo.png}" />

Embed Images from Internet

XAML only:

<Image Source="https://example.com/example.png" />

Using code behind:

// using image from internet
image.Source = ImageSource.FromUri(new Uri("https://example.com/example.png"));
// or simply:
image.Source = "https://example.com/example.png";

Image embeded from Internet is downloaded and cached for 24 hours by default.

To disable cache:

image.Source = new UriImageSource
{
    Uri = new Uri("https://example.com/example.png"),
    CachingEnabled = false
};

To set cache for 5 days:

image.Source = new UriImageSource
{
    Uri = new Uri("https://example.com/example.png"),
    CachingEnabled = true,
    CacheValidity = new TimeSpan(5,0,0,0)
};