首页 > 解决方案 > 如何在 Xamarin 表单上使用 SkiaSharp 加载文件 .svg?

问题描述

如何在 Xamarin Forms(Android 和 iOS)上.svg使用SkiaSharp加载文件。

我尝试使用 SkiaSharp 在 Xamarin 中加载 SVG 文件,但我无法加载它。

我尝试使用SkiaSharp.Extended并参考他们的演示,但仍然无法加载它。

我做错什么了吗?

请帮我!

标签: xamarinxamarin.formsxamarin.androidxamarin.iosskiasharp

解决方案


B1Images >在您的项目中创建一个文件夹Xamarin forms并在此保存图像.svg。确保选择Build Action“EmbeddedResource”

嵌入式资源

B2 > 下载所需的库,例如 :SkiaSharp、、、SkiaSharp.Views.FormsSkiaSharp.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" />

请在SkiaSharp.Extended上查看更多信息


推荐阅读