Forum Xamarin.Forms

App crashes in Skiasharp

Yusuf_AYusuf_A Member ✭✭
edited August 2019 in Xamarin.Forms

I use this function for graphics.

using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using SkiaSharp;
using SkiaSharp.Views.Forms;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Poetry
    public partial class Page1 : ContentPage
        SKBitmap bitmap;
        SKBitmap originalBitmap;

        public Page1(SKBitmap bitmap)
            this.bitmap = bitmap;
            originalBitmap = bitmap;

        private void Canvas_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
            SKImageInfo info = e.Info;
            SKSurface surface = e.Surface;
            SKCanvas canvas = surface.Canvas;
            canvas.Scale((float)e.Info.Width / bitmap.Width);

            SKRect sk = new SKRect(0, 0, bitmap.Width, bitmap.Height);
            canvas.DrawBitmap(bitmap, sk, BitmapStretch.Uniform);

        private void ButtonGenerated_Clicked(object sender, EventArgs e)
            bitmap = originalBitmap;

        private void Graphics()
            SKBitmap newBitmap = new SKBitmap(Convert.ToInt32(bitmap.Width), Convert.ToInt32(bitmap.Height));
            using (SKCanvas canvas = new SKCanvas(newBitmap))
                Random rnd = new Random();
                int rotate = 90 * rnd.Next(1, 5);
                canvas.RotateDegrees(rotate, bitmap.Width / 2, bitmap.Height / 2);
                canvas.DrawBitmap(bitmap, 0, 0);
                canvas.RotateDegrees(-rotate, bitmap.Width / 2, bitmap.Height / 2);

            bitmap = newBitmap;


The code works well but when I call the function several times the application crashes, especially when the bitmap is large or when I use the touchPoints

How do I prevent app crashes.

Thank you in advance.


  • Yusuf_AYusuf_A Member ✭✭

    Anyone have a solution?


  • MattJackMattJack FRMember ✭✭

    Looking at your code there is a memory leak. Indeed you create a bitmap each time you call Graphics, but you never Dispose any bitmap.

    Before replacing bitmap
    bitmap = newBitmap;
    you should try to dispose it:

  • Yusuf_AYusuf_A Member ✭✭

    Thank you very much. that solved my problem.

Sign In or Register to comment.