在我的方案中,我想卡住一个不变的BitmapCacheBrush,然后再在后台任务中进行渲染。不幸的是,我收到错误消息“此Freezable无法卡住”。
是否有任何解决方法或黑客方式卡住也不卡住的对象?
也许可以通过反射设置正确的属性来实现此目标?预先谢谢你们。

编辑:(按要求提供我的示例代码)

 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;
    }

}

最佳答案

首先,您需要弄清楚为什么不能卡住它。进入注册表并将ManagedTracing设置为1(如果必须创建,则为REG_DWORD类型)。我建议您将其添加到regedit的“收藏夹”中,以便在需要打开/关闭它时可以快速获取它。



当您尝试卡住BitmapCacheBrush或检查bool属性BitmapCacheBrush.CanFreeze时,您将在Visual Studio的“输出”选项卡中收到一条警告,告诉您问题出在哪里。

我根据https://blogs.msdn.microsoft.com/llobo/2009/11/10/new-wpf-features-cached-composition/的代码制作了一个测试用例

它给我的警告是:



BitmapCacheBrush.Target的类型为Visual,并且所有Visuals都派生自DependencyObject,而DependencyObject派生自DispatcherObject。并根据https://msdn.microsoft.com/en-us/library/ms750441(v=vs.100).aspx#System_Threading_DispatcherObject



因此,所有视觉效果都是STA,这意味着除非将Target设置为null,否则您将无法卡住BitmapCacheBrush。

10-07 16:48
查看更多