Load SVG file in Xamarin with SkiaSharp

流过昼夜 提交于 2019-12-06 07:19:08

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.

To complete the accepted answer, here is how to load the SKSvg from a URL.

SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg();
using (WebClient client = new WebClient())
{
     svg.Load(new MemoryStream(client.DownloadData(new Uri(ResourceUrl))));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!