I recently talked about some techniques to use RenderTargetBitmap to generate images for your live tiles. Today, we’ll look at some code that goes along with that.
1 | public static async Task SaveTileImage(UIElement control) |
This is the only public facing method, and it has a pretty simple signature. We provide a user control, and it will generate and save all Live Tile images. The names Tile_Wide_100_Name
and Tile_Wide_400_Name
are public constants that are used both by the Image Generator class and the Tile updater class.Tile_Wide_100_Size
and Tile_Wide_400_Size
are constants I define in my projects to hold the required sizes for live tile images according to specs.
To manipulate our rendered bitmap we must first process the raw pixels by using an encoder. The result is an RandomAccessStream that we can use to apply transformations and save to file.
1 | private static async Task<IRandomAccessStream> EncodeBuffer(byte[] pixels, uint width, uint height) |
Lastly, once we have our stream we can start thinking of manipulation and saving to files.
The interesting part is in actually performing the resize and optionally crop for a square tile. We will be using the BitmapTransfrm class for that. The class allows us to apply 4 types of transformations to our image: Scale, Flip, Rotate, Crop. This is also the order in which the transformations are applied and that is important because we need to know what parameters to pass in.
Let’s look at an example and see how this works.
I want to render a 1240x600px image for my 400% wide tile. My DPI is at 175% so the rendered image will be 2170x1050px. To make matters complicated, the square tile (600x600px) is a portion of the bigger wide tile - the right side of it.
If we don’t scale first, and only apply the crop, we only get a small chunk of our image:
So by applying the scaling first, then the crop, we get our desired results
Now that it’s clear how the transform works, here’s the full method that applies it to our encoded buffer and saves our images to disk.
1 | private static async Task SavePixelsToFile(IRandomAccessStream pixels, string fileName, Size scaleSize, Rect cropBox) |
Testing shows that to render one image and save 4 versions of it takes approximately 2s when running on a phone, well below the CPU time threshold.
Leave me a comment or drop me a line if you need any help with this or something similar.