我在“Visual to RenderTargetBitmap”问题上发现了一个新的转折点!
我正在为设计师呈现 WPF 内容的预览。这意味着我需要获取 WPF 视觉对象并将其渲染为位图,而不会显示该视觉对象。有一个很好的小方法来做它喜欢在这里看到它
private static BitmapSource CreateBitmapSource(FrameworkElement visual)
{
Border b = new Border { Width = visual.Width, Height = visual.Height };
b.BorderBrush = Brushes.Black;
b.BorderThickness = new Thickness(1);
b.Background = Brushes.White;
b.Child = visual;
b.Measure(new Size(b.Width, b.Height));
b.Arrange(new Rect(b.DesiredSize));
RenderTargetBitmap rtb = new RenderTargetBitmap(
(int)b.ActualWidth,
(int)b.ActualHeight,
96,
96,
PixelFormats.Pbgra32);
// intermediate step here to ensure any VisualBrushes are rendered properly
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen())
{
var vb = new VisualBrush(b);
dc.DrawRectangle(vb, null, new Rect(new Point(), b.DesiredSize));
}
rtb.Render(dv);
return rtb;
}
工作正常,除了一件小事......如果我的 FrameworkElement 有一个 VisualBrush,那个画笔不会出现在最终渲染的位图中。像这样的东西:
<UserControl.Resources>
<VisualBrush
x:Key="LOLgo">
<VisualBrush.Visual>
<!-- blah blah -->
<Grid
Background="{StaticResource LOLgo}">
<!-- yadda yadda -->
其他所有内容都呈现到位图,但 VisualBrush 不会显示。明显的谷歌解决方案已经尝试过并且失败了。即使是那些特别提到 RTB 位图中缺少的 VisualBrushes 的那些。
我有一个偷偷摸摸的怀疑,这可能是由于它是一个资源,并且那个惰性资源没有被内联。因此,一种可能的解决方法是,以某种方式(???)在渲染之前强制解析所有静态资源引用。但我完全不知道该怎么做。
有人对此有解决办法吗?