I have a background task that should run every N (doesn't matter) minutes to create a UI control and render it to image and save it Pictures Library. I wrote some code here:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var def = taskInstance.GetDeferral();
// creating control
var canvas = new Canvas
{
Height = 100,
Width = 100
};
canvas.Children.Add(new TextBlock { Text = "Hello world" });
var size = new Size(100, 100);
canvas.Measure(size);
canvas.UpdateLayout();
canvas.Arrange(new Rect(0, 0, size.Width, size.Height));
// rendering
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(canvas);
// saving as jpg
var file = await KnownFolders.PicturesLibrary.CreateFileAsync("sample.jpg");
using (var stream = await file.OpenStreamForWriteAsync())
{
var pixelBuffer = await bitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
// convert stream to IRandomAccessStream
var randomAccessStream = stream.AsRandomAccessStream();
// encoding & finish saving
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, randomAccessStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth,
(uint)bitmap.PixelHeight, logicalDpi, logicalDpi, pixelBuffer.ToArray());
await encoder.FlushAsync();
}
def.Complete();
}
But i've got 2 problems here.
We can't create UI element in background, only in UI Thread. Is there any possible way to create it from background task? I've tried many ways to use dispatchers but this didn't work...
Following to this article and this question we can't render an image from control that is not in visual tree of current page. Is there any possible hack of this thing?
Thanks for any help