在我的场景中,我想在后台任务中渲染它之前冻结一个不变的 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;
}
}