Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I render a WPF UserControl to a bitmap without creating a window? I need to render a WPF UserControl and upload it to another program. The bitmaps will be rendered through a Windows Service, so creating a window is not an option (I know there's ways to 'virtually' create windows, but unfortunately anything that calls a command to create a window is NOT an option in my case). Is there a way to RENDER the UserControl without binding it to a Window?

like image 779
bbosak Avatar asked Mar 04 '11 02:03

bbosak


1 Answers

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.

like image 53
RQDQ Avatar answered Sep 23 '22 09:09

RQDQ