【发布时间】:2016-04-13 13:10:11
【问题描述】:
在我的场景中,我想在后台任务中渲染它之前冻结一个不变的 BitmapCacheBrush。不幸的是,我收到错误“无法冻结此 Freezable”。 是否有任何解决方法或hacky方式冻结也不是可冻结的对象? 也许可以通过反射设置正确的属性来达到这个目标?提前谢谢你们。
编辑:(我的示例代码按要求)
public static class ext
{
public static async Task<BitmapSource> RenderAsync(this Visual visual)
{
var bounds = VisualTreeHelper.GetDescendantBounds(visual);
var bitmapCacheBrush = new BitmapCacheBrush(visual);
bitmapCacheBrush.BitmapCache = new BitmapCache();
// We need to disconnect the visual here to make the freezable freezable :). Of course this will make our rendering blank
//bitmapCacheBrush.Target = null;
bitmapCacheBrush.Freeze();
var bitmapSource = await Task.Run(() =>
{
var renderBitmap = new RenderTargetBitmap((int)bounds.Width,
(int)bounds.Height, 96, 96, PixelFormats.Pbgra32);
var dVisual = new DrawingVisual();
using (DrawingContext context = dVisual.RenderOpen())
{
context.DrawRectangle(bitmapCacheBrush,
null,
new Rect(new Point(), new Size(bounds.Width, bounds.Height)));
}
renderBitmap.Render(dVisual);
renderBitmap.Freeze();
return renderBitmap;
});
return bitmapSource;
}
}
【问题讨论】:
-
你能提供一个最小的例子来说明你如何达到不可冻结的 BitmapCacheBrush 的地步吗?
-
冻结无法冻结的对象的唯一方法是回到可以冻结的状态。然后它不再是一个“不可冻结”的对象,你又重新开始工作了。大多数情况下,当我看到这个问题时,这是因为有人试图从错误的线程中冻结对象。但是如果没有好的minimal reproducible example,就无法知道您在这里做错了什么,因此无法正确回答问题。
标签: c# wpf multithreading rendertargetbitmap freezable