简体   繁体   English

使用 SkiaSharp 在 Xamarin 中加载 SVG 文件

[英]Load SVG file in Xamarin with SkiaSharp

From release 1.55.0 SkiaSharp has the support for reading SVG files.从 1.55.0 版开始,SkiaSharp 支持读取 SVG 文件。 The package has been release few days ago (10 Nov. 2016) and I couldn't find enough documentation on how to use it.该软件包已于几天前(2016 年 11 月 10 日)发布,但我找不到有关如何使用它的足够文档。

The following packages are required: SkiaSharp 1.55.0 SkiaSharp Views & Layers 1.55.0 SkiaSharp.Svg 1.55.0-beta1需要以下软件包: 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?第一个问题是在 Xamarin.Android 中加载 SKSvg 的最佳方法是什么?

Here two possible solutions to start working with SkiaSharp that are working for me:这里有两种可能的解决方案来开始与 SkiaSharp 合作,它们对我有用:

Loading SVG from Asset folder (or subfolder):从 Asset 文件夹(或子文件夹)加载 SVG:

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 (eg "subf1/subf2/mysvg.svg").其中“assetSvgFileLoc”是要加载的svgFilename.svg,包括(如果是这种情况)资产文件夹内的路径(例如“subf1/subf2/mysvg.svg”)。

Loading SVG as RAW Resource加载 SVG 作为 RAW 资源

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.在这种情况下,文件位于资源子文件夹“raw”中,“svgName”是我们的 svg 的文件名,没有扩展名。

To complete the accepted answer, here is how to load the SKSvg from a URL.要完成接受的答案,这里是如何从 URL 加载SKSvg

SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg();
using (WebClient client = new WebClient())
{
     svg.Load(new MemoryStream(client.DownloadData(new Uri(ResourceUrl))));
}

I am using this code ,it works great.我正在使用此代码,效果很好。 I can have the SVG in PCL , ios or Android folder Just remember to include the Assembly in path我可以在 PCL 、 ios 或 Android 文件夹中使用 SVG 只需记住在路径中包含程序集

var assembly = this.GetType().GetTypeInfo().Assembly;
using (var s = assembly.GetManifestResourceStream("MyAssembly.Core.Hold.svg"))
{
if (s != null)
{
svg = new SKSvg();
svg.Load(s);
using (SKPaint paint = new SKPaint())
{
canvas.DrawPicture(svg.Picture, paint);
}
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM