以下软件包需要安装SkiaSharp.Views.Forms、SkiaSharp.Extended和SkiaSharp.Svg。从那里我创建了一个自定义 Xamarin.Forms 控件,如下所示:
public class SvgImage : SKCanvasView
{
public static readonly BindableProperty SourceProperty = BindableProperty.Create(nameof(Source), typeof(string), typeof(SvgImage), default(string), propertyChanged: OnPropertyChanged);
public string Source
{
get => (string)GetValue(SourceProperty);
set => SetValue(SourceProperty, value);
}
public static readonly BindableProperty AssemblyNameProperty = BindableProperty.Create(nameof(AssemblyName), typeof(string), typeof(SvgImage), default(string), propertyChanged: OnPropertyChanged);
public string AssemblyName
{
get => (string)GetValue(AssemblyNameProperty);
set => SetValue(AssemblyNameProperty, value);
}
static void OnPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var skCanvasView = bindable as SKCanvasView;
skCanvasView?.InvalidateSurface();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
InvalidateSurface();
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
InvalidateSurface();
}
protected override void OnPaintSurface(SKPaintSurfaceEventArgs e)
{
base.OnPaintSurface(e);
try
{
var surface = e.Surface;
var canvas = surface.Canvas;
canvas.Clear();
if (string.IsNullOrEmpty(Source) || string.IsNullOrEmpty(AssemblyName))
return;
var currentAssembly = Assembly.Load(AssemblyName);
using (var stream = currentAssembly.GetManifestResourceStream(AssemblyName + "." + Source))
{
var skSvg = new SKSvg();
skSvg.Load(stream);
var skImageInfo = e.Info;
canvas.Translate(skImageInfo.Width / 2f, skImageInfo.Height / 2f);
var skRect = skSvg.ViewBox;
float xRatio = skImageInfo.Width / skRect.Width;
float yRatio = skImageInfo.Height / skRect.Height;
float ratio = Math.Min(xRatio, yRatio);
canvas.Scale(ratio);
canvas.Translate(-skRect.MidX, -skRect.MidY);
canvas.DrawPicture(skSvg.Picture);
}
}
catch (Exception exc)
{
Console.WriteLine("OnPaintSurface Exception: " + exc);
}
}
}
我确实必须指定 Svg 图像的程序集和文件夹路径才能找到图像,并且任何 Svg 图像都应设置为 EmbeddedResource。然后在 Xaml 中使用控件:
<controls:SvgImage AssemblyName="SkiaSharpSvgImage" Source="Resources.tux1.svg" />
我创建的整个开源测试项目可以在Github上查看。此外,该 repo 可能会得到改进,但那是我第一次使用 SkiaSharp Svg 图像并测试所有内容。