我发现了“Visual to RenderTargetBitmap”问题的一个新变化!
我正在为设计师渲染WPF预览。这意味着我需要将WPF可视化对象渲染成位图,而不必显示该可视化对象。我有一个不错的小方法来完成它,看看下面的代码:
我正在为设计师渲染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之外的所有内容都会呈现在位图上,但是该VisualBrush却无法显示。已经尝试了明显的谷歌解决方案并且失败了,甚至那些明确提到RTB中缺少VisualBrushes的解决方案也无效。
我有一个狡猾的怀疑,可能是因为它是一种资源,即懒惰资源没有被内联。所以一个可能的解决方法是,在渲染之前以某种方式强制解析所有静态资源引用。但我绝对不知道该如何做到这一点。
有人有解决方法吗?
VisualTreeHelper.GetParent(container)==null ? container : null
是什么意思? - user1228(PresentationSource.FromVisual(container)!=null ? null : FindVisualTreeRoot(container))
,并使用VisualTreeHelper.GetParent查找根的单独FindVisualTreeRoot方法,但我的代码对大多数目的已经足够。 - Ray BurnsViewport3D
,则Viewport3D
不会被渲染。有什么想法吗? - rsbarro