XamSvg for Xamarin.Forms

Getting Started

Quick start

We suppose you used the PCL mobile App template, not a shared project template.

In your PCL project, add a solution folder images then add a logo.svg file to this folder.
Set the build action of the svg file to Embedded resource (right clic on the file > Properties > Build Action).
Then in each of your platform project

  • initialize the XamSvg library
  • add svg to your views

Add the svg component to your app

  • Add the XamSvg component or the XamSvg nuget to all your projects: PCL, Android, iOS and WP81/UWP.

Note that you need a modern PCL profile, ie one with Silverlight unchecked. Read the PCL Profile Change chapter for more informations.

Initialize the XamSvg library

1) Specify in which assembly/ies to search for svg embedded resources in XamSvg.Shared.Config.ResourceAssembly or XamSvg.Shared.Config.ResourceAssemblies (note that ResourceAssemblies overrides ResourceAssembly)
In this tutorial, we put the svg images in the PCL project containing the App class.

public class App : Application
{
    public App()
    {
        XamSvg.Shared.Config.ResourceAssembly = typeof(App).GetTypeInfo().Assembly;
        ...
    }
...

2) Initialize the platform helpers

Add SvgImageRenderer.InitializeForms(); before global::Xamarin.Forms.Forms.Init on each platform

Android

[Activity(Label = "XamSvg Demo", MainLauncher = true, Icon = "@drawable/icon", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SvgImageRenderer.InitializeForms();
        global::Xamarin.Forms.Forms.Init(this, bundle);
    ...

iOS

[Register("AppDelegate")]
public class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        SvgImageRenderer.InitializeForms();
        global::Xamarin.Forms.Forms.Init();
    ...

UW

    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
    ...
            XamSvg.XamForms.Uw.SvgImageRenderer.InitializeForms();
            Xamarin.Forms.Forms.Init(e);
    ...

Add SvgImage to your views

Add the namespace xmlns:svg="clr-namespace:XamSvg.XamForms;assembly=XamSvg.XamForms" to the root tag.
Then add a svg:SvgImage tag:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:svg="clr-namespace:XamSvg.XamForms;assembly=XamSvg.XamForms"
              x:Class="XamSvg.Demo.MainPage">
  <ContentView>
    <StackLayout Orientation="Vertical" VerticalOptions="Start">

        <svg:SvgImage Svg="res:images.logo" HorizontalOptions="Start" HeighRequest="32"
                    ColorMapping="00000000=ff000000" ColorMappingSelected="00000000=ff000000;ffffff=00ff00" />

    </StackLayout>
  </ContentView>
</ContentPage>

Note that as only HeighRequest is set, the SvgImage computes its width automatically according to the aspect ratio of the bounding box defined in the SVG.

Source/BundleName/Svg property

The svg control takes a string as input in the Source property.
If this string starts with res:, the control search the image in the .net embedded resources.
If this string starts with string:, the control reads the svg image from the string.

res: (.NET embedded resources)

For the res: scheme, don't add the .svg extension, and prefix the file name with the directory path relative to the root of your library, while replacing slash by dots.

For exemple if you have this file:

(PCL Project)/MyFiles/Images/tiger_hood.svg

Use this string:

"res:MyFiles.Images.tiger_hood"

The name is case insensitive. You can use res:myfiles.images.tiger_hood if you prefer.

Don't forget to set the build action of tiger_hood.svg to Embedded Resource !

string: (inline svg)

You can dynamically load a svg using an inline string:

var svgString = @"string:<svg viewBox=""0 0 100 100""><circle cx=""50"" cy=""50"" r=""50"" fill=""#ff0000"" /></svg>"; 

Using a timer, you can easily create an animation with this feature. In the timer, modify and set the svg string again. The control will update the image accordingly.

You can also download the svg string from internet and set it this way.

SVG in toolbars images

For Xamarin Forms toolbars images, you can't set a SvgImage. That's where the SvgImageSource class comes handy:

The static SvgImageSource.Create() method will return an ImageSource object containing the rendered SVG at the specified size.

ImageSource SvgImageSource.Create(string svg, double width=0, double height=0, string colorMapping=null)

You have to set either the width or the height or both. There is only one optional color mapping, as ImageSource does not provide pushed state / click events.

SVG in TabbedPage items

Xamarin Forms does not support custom images there. But you can trick it. This article explains how to achieve the magic.

Color Mapping

A color mapping is the transformation of an existing color inside the svg file to another color. This is useful to easily provide a feedback for the pressed state, or to reuse the same svg file using alternate colors.

Colors are specified using the standard HTML syntax: AARRGGBB or RRGGBB
where AA is the alpha level (00=transparent, FF=opaque), and RGB the standard red/green/blue levels.
You can specify color mappings using strings with this syntax:

OLDCOLOR=NEWCOLOR[;OLDCOLOR=NEWCOLOR]...

Examples:

ColorMapping="00000000=ff000000"  
ColorMappingSelected="00000000=ff000000;ffffff=00ff00"

Examples

Complete example projects with source code are provided. Open and try them, they are easy to understand !
These sample projects are also available on github here and may be updated more frequently.

Optimizing SVG images

Why optimize SVG images ? SVG are images described using mathematical curves. The same image can be described by multiple curves. The idea behind our optimizations is to have the simplest description to speed up parsing and the simplest curves to speed up rendering.

Use the free svg image editor Inkscape to modify and generate optimized svg files, to change the bounding box (which controls the aspect ratio), or to simplify the SVG if it is not displayed correctly. Read the Cleaning and optimizing SVG files chapter of this blog post for full information.

You can then use Internet Explorer or Windows Explorer's preview using this SVG preview extension to verify that your optimized SVG still appears correctly.

Reference

SvgImage

Svg Source

  • string Svg

Change colors

  • string ColorMapping
  • string ColorMappingSelected

Respect aspect ratio

  • SvgFillMode FillMode: Fit (respect aspect ratio) / Fill (use full space)

Selection / Highlightning

  • bool IsSelected
  • bool IsHighlightEnabled
  • bool IsSelectionEnabled

Tap (click) Commands

  • ICommand Command
  • object CommandParameter

Unsupported features

SVG files can also be exported from Photoshop and Illustrator, as long as they don't contain bitmaps. Bitmap extensions of svg will not render. You can check for bitmap data in a svg file by opening it and looking for tons of raw bytes.

Main unsupported svg features:

  • embedded bitmaps
  • animations
  • mask groups
  • filters
  • named references other than gradients
  • texts (vote for this feature on uservoice)
  • radial gradients are not supported on UWP. Only linear gradients are supported on UWP. Radial gradients are supported on all other platforms.

Note that css style is supported but not recommended: css parsing is slow compared to xml parsing.

Some SVG icon sources

Get in touch!