Drawing Image from Computed Values

seawolfseawolf USMember

I'm using SkiaSharp to turn computed values into points on the screen. It works fine when I use canvas.DrawPoint(), but this feels like not the right approach:

SKImageInfo info = args.Info;
SKSurface surface = args.Surface;
SKCanvas canvas = surface.Canvas;

canvas.Clear();

SKColor[] colors = new SKColor[] {
    new SKColor(0, 0, 0),
    new SKColor(255, 0, 0),
    new SKColor(0, 255, 0),
    new SKColor(0, 0, 255)
};

for (int i = 0; i < info.Width; ++i)
{
    for (int j = 0; j < info.Height; ++j)
    {
        canvas.DrawPoint(i, j, colors[(i * j) % 4])
    }
}

Note that the computation isn't the point (this just selects a color for each pixel based on a primitive calculation). The point is I am looking for a performant way to first generate all the pixels and then assign them to the canvas in a single step.

It seems this should be possible using an SKBitmap, something like this:

SKImageInfo info = args.Info;

byte[] pixels = new byte[info.Width * info.Height];

for (int i = 0; i < info.Width; ++i)
{
    for (int j = 0; j < info.Height; ++j)
    {
        pixels[i * info.Width + j] = (i*j)%4;
    }
}

SKBitmap bitmap = SKBitmap.Decode(pixels, info);

... and then assign that bitmap to the canvas. However, bitmap is always null after I do this. I am not really clear on how to compute an image rather than reading it from some other source. What am I doing wrong?

Posts

  • KellenLaskKellenLask USMember

    I've also run into this issue. From what I can tell, the most efficient way to generate a bitmap is to create a byte[] and use that array to create a new SKData instance. In a manner similar to this article: http://www.codeguru.com/columns/dotnet/creating-images-from-scratch-in-c.html

  • seawolfseawolf USMember

    I had been looking at that, but what ended up working for me was the following:

    SKColor[] pixels = new SKColor[width * height];
    // do work to assign an SKColor value to each pixel
    bitmap = new SKBitmap(width, height) { Pixels = pixels };
    canvas.DrawBitmap(bitmap, 0, 0);
    
Sign In or Register to comment.