正如Jason所说,FFImageLoading
支持SVG文件。按照以下步骤操作:
在Xamarin.Forms中创建一个资源文件夹而不是Android部分。然后将SVG文件作为嵌入式资源添加。
![enter image description here](https://istack.dev59.com/LYfb4.webp)
用法:使用SvgCachedImage
显示嵌入式SVG图像,并使用TapGestureRecognizer
模拟按钮单击事件。
<ffimageloadingsvg:SvgCachedImage
HeightRequest="50"
Source="resource://XamarinDemo.Resources.brightness2.svg"
WidthRequest="50">
<ffimageloadingsvg:SvgCachedImage.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"></TapGestureRecognizer>
</ffimageloadingsvg:SvgCachedImage.GestureRecognizers>
</ffimageloadingsvg:SvgCachedImage>
不要忘记添加命名空间。
xmlns:ffimageloadingsvg="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
![enter image description here](https://istack.dev59.com/unFAF.gif)
更新:我们可以使用SkiaSharp
来绘制一个 SVG 文件的图像。
MyControl.cs
public class MyControl : Frame
{
private readonly SKCanvasView _canvasView = new SKCanvasView();
public MyControl()
{
Padding = new Thickness(0);
BackgroundColor = Color.Transparent;
Content = _canvasView;
_canvasView.PaintSurface += CanvasViewOnPaintSurface;
}
public static readonly BindableProperty ImageProperty = BindableProperty.Create(
nameof(Image), typeof(string), typeof(MyControl), default(string), propertyChanged: RedrawCanvas);
public string Image
{
get => (string)GetValue(ImageProperty);
set => SetValue(ImageProperty, value);
}
private static void RedrawCanvas(BindableObject bindable, object oldvalue, object newvalue)
{
MyControl svgIcon = bindable as MyControl;
svgIcon?._canvasView.InvalidateSurface();
}
private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
SKCanvas canvas = e.Surface.Canvas;
canvas.Clear();
using (Stream stream = GetType().Assembly.GetManifestResourceStream(Image))
{
SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg();
svg.Load(stream);
SKImageInfo info = e.Info;
canvas.Translate(info.Width / 2f, info.Height / 2f);
SKRect bounds = svg.ViewBox;
float xRatio = info.Width / bounds.Width;
float yRatio = info.Height / bounds.Height;
float ratio = Math.Min(xRatio, yRatio);
canvas.Scale(ratio);
canvas.Translate(-bounds.MidX, -bounds.MidY);
canvas.DrawPicture(svg.Picture);
}
}
}
使用方法:
<local:MyControl
HeightRequest="50"
Image="XamarinDemo.Resources.brightness2.svg"
WidthRequest="50" />
您可以使用 TapGestureRecognizer
来模拟按钮点击事件。