Xamarin Forms and SkiaSharp, implementing moving cursor on bitmap

Nils Kullendorff 21 Reputation points
2021-02-08T17:37:27.06+00:00

I am writing a Xamarin Forms app that loads a bitmap from an embedded resource and uses it as background for a moving cursor. I use a typical event handler for painting the bitmap:

private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
    SKImageInfo info = args.Info;
    SKSurface surface = args.Surface;
    SKCanvas canvas = surface.Canvas;

    canvas.Clear();
    canvas.DrawBitmap(bitmap, info.Rect, BitmapStretch.AspectFill);
}

The cursor is drawn using code like:

private void DrawOverlay()
{
    using (SKCanvas canvas = new SKCanvas(bitmap))
    {
        UserSprite.Draw(locationInPix, rotation, canvas); // static function

        view.InvalidateSurface(); // view is the corresponding SKCanvasView
    }
}

A timer reads the position (GPS) and rotation (compass) and calls the DrawOverlay function periodically. Question: how do I erase the previous cursor image when drawing a new one at a new position without trashing the background bitmap?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,300 questions
0 comments No comments
{count} votes

Accepted answer
  1. JarvanZhang 23,951 Reputation points
    2021-02-09T08:03:28.85+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    how do I erase the previous cursor image when drawing a new one at a new position without trashing the background bitmap

    Do you mean saving the bitmap when clearing the drawing? We cannot do that. When calling the SKCanvas.Clear command to the redraw the canvas, the bitmap will be also cleared. SKCanvas doesn't provide a method to keep the bitmap.

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful