問題:私は背景に、いくつかの他のUI要素(主にテキストブロック)でグリッドを作成し、グリッドをレンダリングし、最後に画像ファイルに保存し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();
}
}
しかし、私は私のバックグラウンドタスクの実行()メソッドからこのメソッドを呼び出しています:メソッドのコードがある
私は例外を少しググと非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