我正在尝试通过使用SkiaSharp软件包动态绘制线条。
我在xaml中定义了控件,如下所示:
<skia:SKCanvasView x:Name="CanvasView" PaintSurface="OnCanvasViewPaintSurface" />
这是我在班级后面的代码:
private SkiaSharp.SKCanvas canvas;
private SkiaSharp.SKSurface surface;
void OnCanvasViewPaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs args)
{
SkiaSharp.SKImageInfo info = args.Info;
surface = args.Surface;
canvas = surface.Canvas;
canvas.Clear();
SkiaSharp.SKPaint thinLinePaint = new SkiaSharp.SKPaint
{
Style = SkiaSharp.SKPaintStyle.Stroke,
Color = SkiaSharp.SKColors.Blue,
StrokeWidth = 6
};
canvas.DrawLine(0, 0, 50, 50, thinLinePaint);
}
上面的部分工作正常,并且在启动时加载视图时将绘制蓝线。但是我要做的是动态绘制新线并删除旧线。
public void DrawNewLine()
{
canvas.Clear();
SkiaSharp.SKPaint thickLinePaint = new SkiaSharp.SKPaint
{
Style = SkiaSharp.SKPaintStyle.Stroke,
Color = SkiaSharp.SKColors.Red,
StrokeWidth = 16
};
canvas.DrawLine(0, 0, 50, 50, thickLinePaint);
}
我正在使用之前声明的canvas字段,但是它不起作用。使用canvas对象时,应用程序将在运行时崩溃。
我究竟做错了什么?
最佳答案
您需要使用SKCanvasView.InvalidateSurface()方法在内部调用OnCanvasViewPaintSurface()。