How to render a WPF UserControl to a bitmap without creating a window How to render a WPF UserControl to a bitmap without creating a window windows windows

How to render a WPF UserControl to a bitmap without creating a window


Have you tried spinning up an instance of the user control and doing something like this:

UserControl control = new UserControl1();control.Measure(new Size(300, 300));control.Arrange(new Rect(new Size(300,300)));RenderTargetBitmap bmp = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Pbgra32);bmp.Render(control);var encoder = new PngBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(bmp));using (Stream stm = File.Create(@"c:\test.png"))   encoder.Save(stm);

It looks like you need to Measure, Arrange. This worked for me.


Ended up using an HwndHost with no actual window.

void cwind()    {        Application myapp = new Application();        mrenderer = new WPFRenderer();        mrenderer.Width = 256;        mrenderer.Height = 256;        HwndSourceParameters myparms = new HwndSourceParameters();        HwndSource msrc = new HwndSource(myparms);        myparms.HwndSourceHook = new HwndSourceHook(ApplicationMessageFilter);        msrc.RootVisual = mrenderer;        myapp.Run();    }    static IntPtr ApplicationMessageFilter(IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)    {        return IntPtr.Zero;    }


Apparently, if you call control.UpdateLayout() after measuring and arranging, the user control doesn't need to be in any window.