Fill in a WriteableBitmap with a solid color (Windows 8 Metro, WinRT)

Posted by Blake on 4/11/2012
)

For those of you that found your way here, you’re probably wanting to learn how to fill in a bitmap with a specific color OR manipulate individual pixels. This example is the first I’ve got working and I will be posting more as I create more and then turn them into reusable objects.

Unfortunately, the ease of System.Drawing.Bitmap’s GetPixel and SetPixel are gone (for now). WinRT will not allow you to access that part of the framework (or many other parts of the framework) even if they exist. Here is my first example on how to fill in a WriteableBitmap with a solid color, pixel by pixel.

In my example, I’ve created a 128x128 WriteableBitmap. Then, you have to return the PixelBuffer as a stream, to do so, Import (using in C#) System.Runtime.InteropServices.WindowsRuntime to allow the AsStream() extension to be called. The other class we’re going to use is Windows.UI.Color (and Windows.UI.Colors) so you may want to include an import to that also.

    Dim bmp As New WriteableBitmap(128, 128)
    Dim stream As Stream = bmp.PixelBuffer.AsStream()
    Dim c As Color = Colors.Red

    For x As Integer = 1 To bmp.PixelWidth
        For y As Integer = 1 To bmp.PixelHeight
            stream.WriteByte(c.B)
            stream.WriteByte(c.G)
            stream.WriteByte(c.R)
            stream.WriteByte(c.A)
        Next
    Next

For each pixel, 4 bytes are written to the stream (Blue, Green, Red, Alpha). Since this is a stream and not an array that’s 128x128 it’s a little harder to get your head around (my natural instinct is to want to write to pixel 6,4). Ideally, I want to create something that has the simplicity of System.Drawing.Bitmap. For now, this is where I’m starting. Hope this helps sometime. Below is C# that has been run through a code converter, I haven’t tried to compile it but I thought I’d share it also.

    WriteableBitmap bmp = new WriteableBitmap(128, 128);
    Stream stream = bmp.PixelBuffer.AsStream();
    Color c = Colors.Red;
    for (int x = 1; x <= bmp.PixelWidth; x++) {
        for (int y = 1; y <= bmp.PixelHeight; y++) {
            stream.WriteByte(c.B);
            stream.WriteByte(c.G);
            stream.WriteByte(c.R);
            stream.WriteByte(c.A);
        }
    }