【发布时间】:2023-03-27 08:03:01
【问题描述】:
我有一个后台任务,应该每 N 分钟(没关系)运行一次,以创建 UI 控件并将其呈现为图像并将其保存为图片库。我在这里写了一些代码:
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();
}
但是我这里有两个问题。
我们不能在后台创建 UI 元素,只能在 UI 线程中创建。有没有可能从后台任务创建它的方法?我尝试了很多使用调度程序的方法,但都没有成功...
在to this article 和this question 之后,我们无法从不在当前页面的可视化树中的控件呈现图像。有没有可能破解这个东西?
感谢您的帮助
【问题讨论】:
-
我过去曾使用 DispatcherTimer 执行类似的任务,没有任何问题。您在使用调度程序时遇到了哪些类型的问题?
-
Doc,我到底应该写什么来使这段代码工作?我试过这个: await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { // 在这里做作业 });当访问 MainWindow 并显示消息“在意外时间调用了一个方法。(来自 HRESULT 的异常:0x8000000E)”等时,我得到 InvalidOperationException。我如何以正确的方式需要访问调度程序?
-
@AMR- 间谍软件? Win 8 App Store 应用程序只能捕获其自身内容的图像——这意味着它已经可以访问屏幕上的所有数据。
-
我很高兴地报告,Windows Phone 8.1 不再是这种情况 - 您现在可以在后台渲染。
-
大家好,我在 WinRT 中将 XAML 元素渲染为位图时遇到了同样的问题“在意外时间调用了一个方法”。该元素位于可视树中。这会得到支持吗?这有点阻碍我们将高速图表库 (www.scichart.com) 移植到 WinRT 的尝试,因为我们依赖 RenderToBitmap 来渲染精灵(标记、散点图)。在 WPF/SL 中效果很好! ...
标签: c# xaml windows-runtime windows-8.1