Load SVG file in Xamarin with SkiaSharp

放肆的年华 提交于 2020-01-23 13:48:06

问题


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?


回答1:


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.




回答2:


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))));
}


来源:https://stackoverflow.com/questions/40692945/load-svg-file-in-xamarin-with-skiasharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!