3
問題:我試圖創建一些其他的UI元素的網格(的TextBlocks大部分),然後使用RenderTargetBitmap
呈現電網和最後將它保存爲圖像文件,在後臺任務如何在UWP後臺任務中使用XAML UI元素?
private async Task<bool> RenderGridAsync()
{
Grid mainGrid = new Grid();
TextBlock tText = new TextBlock()
{
HorizontalAlignment = HorizontalAlignment.Left,
TextWrapping = TextWrapping.Wrap,
Text = "Some Example Text",
VerticalAlignment = VerticalAlignment.Top,
FontSize = 72,
FontWeight = FontWeights.SemiLight
};
mainGrid.Children.add(tText);
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(mainGrid);
var pixelBuffer = await rtb.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView();
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("CurrentImage" + ".png", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
}
}
但是,當我從我的後臺任務,我收到以下錯誤的Run()方法調用此方法
我GOOGLE有一點異常,發現以更新從非UI線程的UI元素,我需要使用這樣的:
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher
.RunAsync(CoreDispatcherPriority.Normal, async() => {
await RenderGridAsync();
});
但即使這是給我一個例外:
Exception thrown: 'System.Runtime.InteropServices.COMException' in BackgroundTask.winmd
WinRT information: Could not create a new view because the main window has not yet been created
從我得到的信息可以看出,在UI元素可以添加到它之前,我需要呈現網格並將其保存到後臺任務中的圖像。 以前,我在Windows Phone 8.1中實現了這個沒有任何問題。
是不是可以在後臺任務或非UI任務上使用UI元素? 如果是,我該怎麼做?
這正是我需要的..!實現XamlRenderingBackgroundTask並重寫OnRun(IBackgroundTaskInstance taskInstance)方法解決了我的問題。 – Pratyay