在 Xamarin 本机项目中使用 SkiSharp

Using SkiSharp in a Xamarin native project

native Xamarin 项目中使用 SkiaSharp 的最佳方法是什么? 目标是编写一次 canvasView 并在 iOS 和 Android 之间共享它们。

我第一次尝试这样做是创建一个 iOS 和 Android 项目引用的共享项目。使用这种方法我可以做这样的事情。

using System;
using SkiaSharp;
#if __IOS__
using SkiaSharp.Views.iOS;
using Foundation;
#elif __ANDROID__
using SkiaSharp.Views.Android;
using Android.Content;
using Android.Runtime;
using Android.Util;
#endif

namespace SkiaComponents
{
    [Register("TestView")]
    public class TestView : SKCanvasView
    {
#if __ANDROID__
        public TestView(Context context) : base(context)
        {
        }

        public TestView(Context context, IAttributeSet attrs) : base(context, attrs)
        {
        }

        public TestView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
        {
        }

        protected TestView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
        {
        }
#endif

        protected override void OnPaintSurface(SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info = args.Info;
            SKSurface surface = args.Surface;
            SKCanvas canvas = surface.Canvas;

            canvas.Clear();

            var paint = new SKPaint {Style = SKPaintStyle.Stroke, Color = SKColors.Blue, StrokeWidth = 25};

            canvas.DrawCircle(info.Width / 2, info.Height / 2, 100, paint);
        }
    }
}

然而,这对我来说有点笨拙。有没有更好的方法?

我不认为使用#ifdefs 是最好的方法。在没有 #ifdef 的情况下在每个平台项目上原生使用 SKCanvasView 并调用公共代码绘制到 Canvas。使用通用绘图代码创建 class 库 - 与每个平台共享(甚至可以是网络)。 使用 netstandard 的优势 - 它仍然可以引用 SkiaSharp NuGet - 编译应用程序时将使用每个平台的本机。

Android/iOS代码:

        protected override void OnPaintSurface(SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info = args.Info;
            SKSurface surface = args.Surface;
            SKCanvas canvas = surface.Canvas;
            CommonCode.DrawCanvas1(canvas, info);
        }

常用代码(netstandard20库)

        private void DrawCanvas1(SKSurface surface, SKImageInfo info)
        {
            using var paint = new SKPaint {Style = SKPaintStyle.Stroke, Color = SKColors.Blue, StrokeWidth = 25};

            canvas.DrawCircle(info.Width / 2, info.Height / 2, 100, paint);
        }

我使用这种方法在 3 个不同的平台(iOS、Android、WPF)上使用 SkiaSharp。我认为 Xamarin Native 有很好的好处 - 与 Xamarin Forms 相比,你更接近硬件,应用程序通常更小,启动更快并且仍然可以重用大量代码。