1

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.

  1. 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...

  2. 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

4

1 回答 1

0

我在 MSDN 论坛上问了一些相关的问题。我的复制代码可能会对您有所帮助。在重现代码中,我将 CoreApplicationView 创建为后台 UI 线程,然后调用 RenderAsync 为目标 UIElement 生成图像。这个重现代码对我来说有一些问题,但它可能对你有用。

我的问题在这里

于 2014-03-21T08:35:44.263 回答