如何在Xamarin.Forms中脱离SKPaintSurfaceEventArgs使用SkiaSharp绘图
适配方案步骤
1. 布局SKCanvasView
在Xamarin.Forms页面的XAML或代码中添加SKCanvasView控件:
- XAML方式:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:skia="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms" x:Class="YourNamespace.YourPage"> <skia:SKCanvasView x:Name="canvasView" /> </ContentPage>
- 代码方式(在页面构造函数中):
var canvasView = new SKCanvasView(); Content = canvasView;
2. 抽离独立的绘图逻辑方法
把原来WinForms事件处理器中的绘图代码,抽成一个可复用的方法,接收SKCanvas和SKImageInfo参数:
private void DrawCustomContent(SKCanvas canvas, SKImageInfo info) { // 这里放你的绘图代码,比如: canvas.Clear(SKColors.White); using var paint = new SKPaint { Color = SKColors.Red, Style = SKPaintStyle.Fill }; canvas.DrawRect(new SKRect(50, 50, 200, 200), paint); paint.Color = SKColors.Black; paint.TextSize = 24; canvas.DrawText("适配Xamarin.Forms绘图", 50, 300, paint); }
3. 关联PaintSurface事件
在页面的初始化逻辑(比如构造函数、OnAppearing方法)中,将SKCanvasView的PaintSurface事件绑定到上面的绘图方法:
public YourPage() { InitializeComponent(); canvasView.PaintSurface += (sender, e) => DrawCustomContent(e.Surface.Canvas, e.Info); }
4. 外部触发绘图
要在自定义方法或其他事件(如按钮点击)中触发绘图,不要直接调用DrawCustomContent,而是通过调用InvalidateSurface()触发SKCanvasView重绘,进而执行绘图逻辑。如果需要动态调整绘图参数,可通过类级变量传递:
示例:按钮点击切换绘图颜色
- 定义类级变量存储绘图参数:
private SKColor _currentDrawColor = SKColors.Red;
- 修改
DrawCustomContent方法使用该变量:
private void DrawCustomContent(SKCanvas canvas, SKImageInfo info) { canvas.Clear(SKColors.White); using var paint = new SKPaint { Color = _currentDrawColor, // 使用动态变量 Style = SKPaintStyle.Fill }; canvas.DrawRect(new SKRect(50, 50, 200, 200), paint); }
- 按钮点击事件中更新参数并触发重绘:
private void OnSwitchColorBtnClicked(object sender, EventArgs e) { _currentDrawColor = _currentDrawColor == SKColors.Red ? SKColors.Blue : SKColors.Red; canvasView.InvalidateSurface(); // 触发重绘 }
注意事项
- 确保已安装
SkiaSharp.Views.FormsNuGet包(而非仅SkiaSharp),这是Xamarin.Forms中SKCanvasView的依赖包。 - 绘图资源(如
SKBitmap、SKShader)需使用using语句或在页面销毁时释放,避免内存泄漏。 - Xamarin.Forms中SKCanvas的坐标系统与WinForms一致,原点在控件左上角,无需额外坐标转换。
内容的提问来源于stack exchange,提问作者user22973130
相关产品推荐
相关产品推荐

