【发布时间】:2018-08-13 13:00:15
【问题描述】:
我一直在渲染窗口中未显示的用户控件的黑色/空白图像。 UserControl 包含 LiveChart 的 CartesianChart 和一些 UIElements。首先,我从SO: C# chart to image with LiveCharts
和Github: Live-Charts/ChartToImageSample.xaml.cs 借用了解决方案,并将SaveToPng 和EncodeVisual 应用于运行时生成的简单UIControl(未添加或显示在窗口中),它有效。
Canvas control = new Canvas() { Width=100, Height=100, Background = new SolidColorBrush(Colors.Pink)};
control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
control.Arrange(new Rect(0, 0, control.DesiredSize.Width, control.DesiredSize.Height));
control.UpdateLayout();
SaveToPng(control, @"C:\Foo.png");
private void SaveToPng(FrameworkElement visual, string fileName)
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
EncodeVisual(visual, fileName, encoder);
}
private static void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
BitmapFrame frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (FileStream stream = File.Create(fileName)) encoder.Save(stream);
}
但是当我将相同的逻辑应用到 UserControl 时
UserControl control = new UserControl(params)
// canvas.Children.Add(control); <-- if comment out, output blank/black image
control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
control.Arrange(new Rect(0, 0, control.DesiredSize.Width, control.DesiredSize.Height));
foreach (CartesianChart cc in FindVisualChildren<CartesianChart>(control))
{
cc.Update(true, true); //force chart redraw
}
control.UpdateLayout();
SaveToPng(control, @"C:\Foo.png");
<!-- UserControl XAML -->
<UserControl>
<Grid>
<Border>
<Grid>
<Label></Label>
<Label></Label>
<Label></Label>
<CartesianChart DisableAnimations="True"></CartesianChart>
</Grid>
</Border>
</Grid>
</UserControl>
输出一个空白/黑色图像。只有当我将 UserControl 添加到存在并在窗口/XAML 上可见的 UIControl 中时,UserControl 才会正确呈现到图像(例如canvas.Children.Add(lc))。然后我还尝试了SO: How to render a WPF UserControl to a bitmap without creating a window 中描述的解决方案,但我得到了相同的结果——即我需要先将此 UserControl 添加到可见的 UIControl,无论我是否在 UserControl 上执行UpdateLayout。
为什么第一个示例(Canvas)被渲染,而不是第二个示例(UserControl)?有什么区别,我该如何解决?
【问题讨论】:
标签: c# wpf livecharts