Search code examples
xamarin.formsskiasharp.net-maui

How do I create a new SKBitmap that is black (empty) but opaque?


I am using .net maui and skiasharp, and I'm new to both. When I create a new SKBitmap and display it, I find it is transparent unless I manually loop through and set the alpha channel to 255. Is there a way to create an image that's fully opaque from the start instead of fully transparent? I want the image to be Bgra8888.

I tried:

    SKBitmap dstBitmap = new SKBitmap(width, height);
    SKBitmap dstBitmap = new SKBitmap(width, height, false);
    SKBitmap dstBitmap = new SKBitmap(width, height, true);
    SKBitmap dstBitmap = new SKBitmap(width, height, SKColorType.Bgra8888, SKAlphaType.Opaque);

but the 4th byte (alpha) of every pixel is still 0 and I find I need to loop through every pixel and set that byte to 255 in order to see anything before I draw it to a canvas.

    byte* dstPtr = (byte*)dstBitmap.GetPixels().ToPointer();
    ...
    for (int y = 0; y < height; ++y)
    {
        for (int x = 0; x < width; ++x)
        {
            dstPtr += 3;
            *dstPtr++ = 0xFF;
        }
    }
    ... elsewhere...
    canvas.DrawBitmap(myBitmap, myRect);

I can of course just create my own method to create images in this way, which I have, but it seems different from what I've experienced in the past on other platforms, though maybe that's because I typically wouldn't have an alpha channel at all, just RGB888, but that's not an option in skia, so I'm wondering if I'm missing something. Thank you


Solution

  • Can fill the bitmap with solid color, once you have a Canvas for it:

    using Xamarin.Forms;
    using SkiaSharp;
    // Extension Methods.
    using SkiaSharp.Views.Forms;
    
    SKCanvas canvas = new SKCanvas(skbitmap);
    // Xamarin.Forms.Color.ToSKColor is in static class "Extensions".
    canvas.Clear(Color.Black.ToSKColor());
    

    Note: In a draw method, you might instead have a Surface surface for the bitmap; the canvas is then surface.Canvas.