Jerry Nixon @Work: Decorate your tree with XAML

Jerry Nixon on Windows

Wednesday, December 18, 2013

Decorate your tree with XAML

ImageNext week is Christmas. I know most of you are scrambling to find the perfect gift for that special someone. Here’s an idea: a custom app built just for her. What could she love more than vector-based graphics on a touch screen? How she’ll remember this year and bring it up again and again, reminding you of what you gave her. And, what’s better than Christmas leftovers? How about a post-Christmas bug/fix/triage session in the comfort of your own home!

Seriously, I am not being serious. But if you are wanting to build a Windows 8.1 app that uses the new Render Target Bitmap capability, then look no further than this simple demo that will walk you through creating a Christmas tree, arranging the ornaments and saving the result.

RenderTargetBitmap class

MSDN: Represents an image source that can be populated with the combined contents of a XAML visual tree. See Remarks for some notable limitations on which XAML visuals can be captured in a RenderTargetBitmap. Using a RenderTargetBitmap, you can accomplish scenarios such as applying image effects to a visual that originally came from a XAML UI composition, generating thumbnail images of child pages for a navigation system, or enabling the user to save parts of the UI as an image source and then share that image with other apps. Because RenderTargetBitmap is a subclass of ImageSource, it can be used as the image source for Imageelements or an ImageBrush brush.

Let’s see how it is done

In the video above, I walk you through creating a dynamic XAML app that shows a Christmas tree, allowing the user to decorate it the way they want. Then, using the Render Target Bitmap, the user can save their creation to an image file on their local machine.

The trick to the save is this block:

image

The whole thing is in the CaptureAndSave() method that handles the rendering and the saving of the resulting ImageSource to a destination the user chooses. This includes the BitmapEncoder which is used to save the file as a JPEG.

The code to pick the destination is this block:

image

Get all the code here.

Conclusion

Does your app have to be a Christmas theme in order to get the RenderTargetBitmap to work property? :) Yes. Yes, it does. That’s the way the API was written. Strange, I know. So if you want to render any part of your XAML application to the file system, you will need to make sure there’s a Christmas tree involved. And, no, I am not being serious. But, I am being serious when I tell you to have a great Christmas holiday this year! See you next year.

Best of luck!