SkiaSharp跨平台绘图研究2-Xamarin.Forms移动应用
SkiaSharp跨平台绘图研究2-Xamarin.Forms移动应用
继续之前的SkiaSharpDemo解决方案。
微软官网有Xamarin.Forms采用SkiaSharp绘图的详细介绍。
https://docs.microsoft.com/zh-cn/xamarin/xamarin-forms/user-interface/graphics/skiasharp/
创建Xamarin.Forms项目
项目名称XamarinDemo,只选择了安卓平台,空白初始屏幕,简单一点。
给XamarinDemo项目NuGet安装SkiaSharp.Views.Forms 2.80.3
在MainPage.xaml上添加一个SKCanvasView容器,存放画布,页面xaml代码非常相似。
<StackLayout> <Button x:Name="btnRefresh" Text="绘图" Margin="4"></Button> <skia:SKCanvasView x:Name="skContainer" HeightRequest="300" Margin="4"> </skia:SKCanvasView> </StackLayout>
MainPage.xaml.cs的绘图代码,跟WPF项目几乎一样。
public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); btnRefresh.Clicked += BtnRefresh_Clicked; skContainer.PaintSurface += SkContainer_PaintSurface; } private void BtnRefresh_Clicked(object sender, EventArgs e) { Debug.WriteLine($"{DateTimeOffset.Now}, 刷新画布"); //强制画布重绘 skContainer.InvalidateSurface(); } private void SkContainer_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e) { var canvas = e.Surface.Canvas; canvas.Clear(SKColors.SkyBlue); var paint = new SKPaint { Color = SKColors.Black, IsAntialias = true, Typeface = SkiaChinaFont.ChinaFont, TextSize = 48 }; string msg = $"{DateTimeOffset.Now:T}, 还有1万行Skia绘图代码..."; canvas.DrawText(msg, 0, 60, paint); var linePaint = new SKPaint() { Color = (DateTimeOffset.Now.Second % 4 <= 1) ? SKColors.Red : SKColors.Green, Style = SKPaintStyle.Stroke,//不填充 StrokeWidth = 3, }; canvas.DrawRect(10, 90, e.Info.Width - 20, e.Info.Height - 150, linePaint); msg += $", linePaint.Color={linePaint.Color}, skContainer.CanvasSize={skContainer.CanvasSize}"; Debug.WriteLine(msg); } }
加载中文字库
安卓项目不太方便复制字体文件去APP目录,把DroidSansFallback.ttf设置为嵌入的资源,按照资源文件的方式去加载。
/// <summary> /// Skia中文字体 /// </summary> public static class SkiaChinaFont { public static SKTypeface ChinaFont { get; private set; } static SkiaChinaFont() { //加载资源方案,设置字体文件属性为嵌入的资源 var fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("XamarinDemo.DroidSansFallback.ttf"); ChinaFont = SKTypeface.FromStream(fontStream); } }
运行测试
在VS2022自带的安卓模拟器上跑起来,绘图出来了,可以更新。
DEMO源代码参见:https://gitee.com/woodsun