Corrado's Blog 2.0

Online thoughts of a technology funatic

Save Win2D CanvasControl content

Win2D is an easy-to-use Windows Runtime API for immediate mode 2D graphics rendering with GPU acceleration that is very helpful in some situations like real time or layered rendering.
This post is about how to save dynamically rendered content to a file for further external processing.

To give you an idea, let’s build a quick Win2D sample.

Create a blank new UWP project and add a NuGet reference to Win2D package

image

on MainPage.Xaml add following XAML

and this code on relative codebehind

if you now run the sample and change the value of the slider you will see the rectangle moving this way

cb

From the code is evident that each time the value of the slider changes we invalidate the CanvasControl so that OnDraw method gets called and content is redrawn with the new rectangle position.

To save CanvasControl content we basically need to draw actual content into an offscreen render target and use the SaveAsync method to get the stream content.
Here’s the code:

code just draws the same content into a CanvasRenderTarget representing the offscreen renderer and then gets that stream, the remaining code just saves it into a StorageFile.
Off course what’s drawn into offscreen renderer is up to you (as example you might add a watermark) and output format can be changed via CanvasFormatBitmap parameter.

HTH