Friday, 28 June 2013

Windows 8.1 RenderTargetBitmap

RenderTargetBitmap is a new feature in Windows 8.1 which allows XAML trees to be rendered to Bitmap:

I've previously written 2 articles about using Direct2D to render 2D drawings in Windows 8 apps and export them to file, which prior to 8.1 was the only way of doing this.

This is how to render the tree using RenderTargetBitmap:

var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(myElementTree);

myImage.Source = renderTargetBitmap;

And then output to file:

var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.Render(myElementTree);
var pixels = await renderTargetBitmap.GetPixelsAsync();

var picker = new FileSavePicker();

// Picker setup
var file = await picker.PickSaveFileAsync();
// File validation

using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)

    var encoder = await 
        BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
    encoder.SetPixelData(BitmapPixelFormat.Rgba8, 100, 0, 96, 96,         
        await renderTargetBitmap.GetPixelsAsync());
    await encoder.FlushAsync();

[Samples from here]

This opens up a lot of imaging opportunities for developers wanting to do imaging in apps who don't want to get into Direct2D.

Direct2D however, still has benefits like built-in effects, opacity mask capability (8.1 still doesn't seem to have this but I may be wrong).

No comments:

Post a Comment