我正在尝试创建一些图表图像,而不在屏幕上显示这些图表。我已经这样做了很长一段时间,尝试了很多不同的方法,但似乎都不起作用。如果我先在窗口中显示图表,代码就会很好地工作,但是如果我不在窗口中显示它,位图就只是白色和黑色边框(不知道为什么)。
我尝试在呈现之前将图表添加到边框中,并为边框提供绿色的borderBrush。在位图中,我看到绿色的borderBrush,然后是黑色的边框和白色的背景,但没有图表。图表不是包含在黑色边界中,所以我不知道它是从哪里来的。
我尝试在不调用window.Show()的情况下将图表添加到窗口中,再次得到黑色边框和白色背景。但是,如果我调用window.Show(),位图将包含该图表。
我试着使用here解释的drawingVisual,同样的结果。
下面是代码(不包括将元素添加到边框或窗口):
private static BitmapSource CreateElementScreenshot(FrameworkElement element, int dpi)
{
if (!element.IsMeasureValid)
{
Size size = new Size(element.Width, element.Height);
element.Measure(size);
element.Arrange(new Rect(size));
}
element.UpdateLayout();
var scale = dpi/96.0;
var renderTargetBitmap = new RenderTargetBitmap
(
(int)(scale * element.RenderSize.Width),(int)(scale * element.RenderSize.Height),dpi,dpi,PixelFormats.Default
);
// this is waiting for dispatcher to perform measure, arrange and render passes
element.Dispatcher.Invoke(((Action)(() => renderTargetBitmap.Render(element))), DispatcherPriority.Render);
return renderTargetBitmap;
}注意:该图表是一个ContentControl。
有没有什么办法我可以让图表呈现,而不是先在窗口中显示它?
发布于 2010-05-11 23:18:00
调用element.ApplyTemplate()完成了任务。
发布于 2014-02-05 20:55:54
如果有人在渲染StackPanel中的RenderTargetBitmap (获取白色/空图像)项目时遇到类似的问题,可以将其临时移动到网格,然后渲染并将其放回StackPanel中
Grid grid = new System.Windows.Controls.Grid() { Background = Brushes.White, Width = iWidth, Height = iHeight };
Panel panel = plot.Parent as Panel;
if (panel != null)
{
panel.Children.Remove(plot);
grid.Children.Add(plot);
grid.Measure(new Size(iWidth, iHeight));
grid.Arrange(new Rect(new Size(iWidth, iHeight)));
}
plot.Measure(new Size(iWidth, iHeight));
plot.Arrange(new Rect(new Size(iWidth, iHeight)));
plot.ApplyTemplate();
plot.UpdateLayout();
grid.ApplyTemplate();
grid.UpdateLayout();
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(
iWidth,
iHeight,
96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(grid);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
MemoryStream memoryStream = new MemoryStream();
encoder.Save(memoryStream);
bitmap = new System.Drawing.Bitmap(memoryStream);
if (panel != null)
{
grid.Children.Remove(plot);
panel.Children.Add(plot);
}
plot.Measure(new Size(iWidthBefore, iHeightBefore));
plot.Arrange(new Rect(new Size(iWidthBefore, iHeightBefore)));
plot.UpdateLayout();发布于 2015-12-02 23:16:42
对我来说,调用element.Arrange()是缺少的一部分。
https://stackoverflow.com/questions/2562310
复制相似问题