I’ve been tackling with an issue this morning to store the drawing on an InkCanvas as an image in a StorageFile. After hunting online for possible resolutions, I came across Mike Taulty’s blog post from a month ago which outlined a very similar issue.

For some of my older projects, I created an extension that uses RenderTargetBitmap to render a UI element out to an image in a StorageFile. Attempting to use this same method on the InkCanvas however has a different effect, one that wouldn’t work for my app (possibly wouldn’t be desired for any app). The issue is that when you call the RenderAsync method and pass through your InkCanvas or a parent element of the InkCanvas in your XAML, the end result is a blank saved image and your InkCanvas blanks itself too until you resize the app’s window, at which point, the drawing comes back.

Reading into Mike’s post, it was clear that the way of getting the ink out of an InkCanvas into an image is to use Win2D which is capable of rendering the strokes of an InkCanvas into a Buffer or array of bytes representing the drawing which you can then use to either show or save the image.

Seeing that Mike had this similar issue in his project, I adapted my previous code for saving UI elements as images into a specific extension for the InkCanvas using an adapted version of Mike’s solution. Here is what that looks like:

If you can’t see the code above, you can find it by clicking here.

There is a slight gotcha with how this works though. As I explained earlier, calling RenderAsync on the InkCanvas will cause the control to act up and hide your drawing. To rectify this issue in the control I’ve built for keeping a common drawing experience, I had to take the InkCanvas out of the Grid I had it in, and layered them so the Grid was below the InkCanvas but still passed that through as the root element. This means that the InkCanvas doesn’t get caught up in the RenderAsync method. It will look like this:

Again if you can’t see the code above, you can find it here.

This should have you now up and running with drawing on the InkCanvas and saving out the drawing using the provided extension method. If you have any problems, let me know and I’ll do my best to help! If you have a better solution, feel free to post in the comments!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.