Visual brush using control which isn't rendered?

丶灬走出姿态 提交于 2019-12-02 05:46:50

Before rendering the control you would have to manually do its layout by calling Measure and Arrange. This requires that you specify the desired size of the control, e.g. by explicitly setting its Width and Height properties.

There is no need for VisualBrush and DrawingVisual, you can directly render the control to the RenderTargetBitmap.

chartControl1.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
chartControl1.Arrange(new Rect(0, 0, chartControl1.Width, chartControl1.Height));
chartControl1.UpdateLayout();

var bmp = new RenderTargetBitmap((int)chartControl1.ActualWidth,
    (int)chartControl1.ActualHeight, 96, 96, PixelFormats.Pbgra32);

bmp.Render(chartControl1);

If the control calculates a preferred size during layout (in Measure), you could perhaps use its DesiredSize property for rendering.

chartControl1.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
chartControl1.Arrange(new Rect(new Point(), chartControl1.DesiredSize));
chartControl1.UpdateLayout();

Note also that the rendering thread's ApartmentState must be STA. In a console application you could simply apply the STAThread attribute to the Main method.

[STAThread]
static void Main(string[] args)
{
    ...
}

I tried Measure(), Arrange(), etc, then discovered that these DO work if the Visual has a parent! In my case I was removing the Visual from one container, updating its properties (colour, etc), then trying to use it as a VisualBrush and it wasn't getting updated. Leaving it in the original container for the duration of Measure() and Arrange() fixed it (even though it was all done offscreen).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!