简体   繁体   中英

Dynamically draw lines with SkiaSharp in Xamarin

I'm trying to dynamically draw lines by using the package SkiaSharp.

I've defined the control in my xaml like this:

<skia:SKCanvasView x:Name="CanvasView" PaintSurface="OnCanvasViewPaintSurface" />

This is my code behind class:

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);
}

The part above works fine, and a blue line will be drawn when loading the view at startup. But what I want to do is to dynamically draw new lines and remove the old ones.

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);
}

I am using the canvas field that was declared before, but it's not working. Application will crash at runtime when using the canvas object.

What am I doing wrong?

您需要使用SKCanvasView.InvalidateSurface()方法在内部调用OnCanvasViewPaintSurface()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM