ContentControl + RenderTargetBitmap +空图像 [英] ContentControl + RenderTargetBitmap + empty image
问题描述
我试图创建一些图表图像,而不在屏幕上显示这些图表。我已经花了很长时间了,尝试了很多不同的方法,但是似乎没有任何效果。如果我先在窗口中显示图表,则代码可以正常工作;但是,如果我不在窗口中显示图表,则位图只是白色且带有黑色边框(不知道为什么)。
Im trying to create some chart images without ever displaying those charts on the screen. I'v been at this for quite a while and tried a lot of different things but nothing seems to work. The code works perfectly if I display the chart in a window first, but if I don't display it in a window, the bitmap is just white with a black border (no idea why).
我尝试在渲染之前将图表添加到边框,并为边框提供绿色的borderBrush。在位图中,我看到绿色的边框画笔,然后是黑色的边框和白色背景,但没有图表。该图表不包含在黑色的边界中,所以我不知道它来自哪里。
I have tried adding the chart to a border before rendering and giving the border a green borderBrush. In the bitmap, I see the green borderBrush then the black border and white background but no chart. The Chart is not contained in a black boarder so I don't know where that is coming from.
我尝试将图表添加到窗口中而不调用window.Show ()再一次,我得到了黑色寄宿生和白色背景。但是,如果我调用window.Show(),则位图将包含图表。
I have tried adding the chart to a window without calling window.Show() and again I just get the black boarder and white background. However if I call window.Show() the bitmap contains the chart.
我已尝试使用drawingVisual进行解释,如此处,结果相同。
I have tried using a drawingVisual as explained here, same result.
以下是代码(不包括将元素添加到边框或窗口中):
Here is the code (not including adding the element to a border or window):
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。
Note: The chart is a ContentControl.
反正我可以在不首先显示在窗口中的情况下显示图表吗?
Is there anyway I can get the chart to render without displaying it in a window first?
推荐答案
调用element.ApplyTemplate()可以达到目的。
Calling element.ApplyTemplate() did the trick.
这篇关于ContentControl + RenderTargetBitmap +空图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!