xamarin - 如何在 Xamarin 表单上使用 SkiaSharp 加载文件 .svg?
问题描述
如何在 Xamarin Forms(Android 和 iOS)上.svg
使用SkiaSharp加载文件。
我尝试使用 SkiaSharp 在 Xamarin 中加载 SVG 文件,但我无法加载它。
我尝试使用SkiaSharp.Extended并参考他们的演示,但仍然无法加载它。
我做错什么了吗?
请帮我!
解决方案
B1Images
>在您的项目中创建一个文件夹Xamarin forms
并在此保存图像.svg
。确保选择Build Action
“EmbeddedResource”
B2 > 下载所需的库,例如
:SkiaSharp
、、、SkiaSharp.Views.Forms
SkiaSharp.Extended.Svg
B3 > 在behind code
, 在 Page 的构造函数处使用方法LoadSvg(xCanvasView.AutomationId)
( Example
: Page is ListNewConversationPage
)。并声明所需的功能:
private SKSvg svg;
// Get file .svg to folder Images
private static Stream GetImageStream(string svgName)
{
var type = typeof(ListNewConversationPage).GetTypeInfo();
var assembly = type.Assembly;
var abc = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.Images.{svgName}");
return abc;
}
private void LoadSvg(string svgName)
{
// create a new SVG object
svg = new SKSvg();
// load the SVG document from a stream
using (var stream = GetImageStream(svgName))
svg.Load(stream);
}
private void OnPageAppearing(object sender, EventArgs e)
{
svg = null;
var page = (ContentPage)sender;
LoadSvg(page.AutomationId);
var canvas = (SKCanvasView)page.Content;
canvas.InvalidateSurface();
}
private void OnPainting(object sender, SKPaintSurfaceEventArgs e)
{
try
{
var surface = e.Surface;
var canvas = surface.Canvas;
var width = e.Info.Width;
var height = e.Info.Height;
// clear the surface
canvas.Clear(SKColors.White);
// the page is not visible yet
if (svg == null)
return;
// calculate the scaling need to fit to screen
float scaleX = width / svg.Picture.CullRect.Width;
float scaleY = height / svg.Picture.CullRect.Height;
var matrix = SKMatrix.MakeScale(scaleX, scaleY);
// draw the svg
canvas.DrawPicture(svg.Picture, ref matrix);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
B4 > 在.xaml
文件中,与.svg
图像一起使用image_part_circle.svg
<forms:SKCanvasView x:Name="xCanvasView"
PaintSurface="OnPainting"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
BackgroundColor="Blue"
AutomationId="image_part_circle.svg" />
推荐阅读
- javascript - 如何解决未捕获的 TypeError:无法读取属性“字段”制表符
- c++ - ADL 不能在外面工作(即使是结构)
- python - Python 停止生成器中的进程
- amazon-web-services - SNS FIFO 主题不将消息扇出到 SQS FIFO 队列
- node.js - 在 Mikro-ORM 中多次分叉 EntityManager 意味着什么?
- odata - 简单的 OData 客户端 - 在运行时创建 OrderBy 表达式?
- mysql - 如何使用 Rails 中的 update_all() 方法传递可变参数值?
- kubernetes - 字段“resource.subnetwork”的值无效。如果网络资源处于自定义子网模式,网络接口必须指定子网
- r - 从 sliderInput 更新 rhandsontable
- javascript - Godot 无法在 python 烧瓶服务器上加载 .pck 文件;任何人都可以建议修复吗?