Search code examples
androidsvgxamarinxamarin.androidskiasharp

Load SVG file in Xamarin with SkiaSharp


From release 1.55.0 SkiaSharp has the support for reading SVG files. The package has been release few days ago (10 Nov. 2016) and I couldn't find enough documentation on how to use it.

The following packages are required: SkiaSharp 1.55.0 SkiaSharp Views & Layers 1.55.0 SkiaSharp.Svg 1.55.0-beta1

The first question is what's the best way to load an SKSvg in Xamarin.Android?


Solution

  • Here two possible solutions to start working with SkiaSharp that are working for me:

    Loading SVG from Asset folder (or subfolder):

    public SKSvg LoadAnSvgFromAssets(Context ctx, string assetSvgFileLoc)
        {
            var assets = ctx.Assets;
            var svg = new SKSvg();
            using (var stream = new StreamReader(assets.Open(assetSvgFileLoc)))
                {
                  svg.Load(stream.BaseStream);
                  return svg;
                }
        }
    

    where "assetSvgFileLoc" is the svgFilename.svg to load, including (if it's the case) the path inside Asset folder (e.g. "subf1/subf2/mysvg.svg").

    Loading SVG as RAW Resource

    public SKSvg LoadAnSvgFromResources(Context ctx, string svgName))
      {
        var resId = ctx.Resources.GetIdentifier(svgName, "raw", ctx.PackageName);           
        var svg = new SKSvg();
        using (var stream = ctx.Resources.OpenRawResource(resId))
        {
            svg.Load(stream);
            return svg;
        }
    }
    

    In this case the file is inside the Resources subfolder "raw" and the "svgName" is the filename of our svg without extension.