Render a "not visible" WPF controls to an bitmap image Render a "not visible" WPF controls to an bitmap image wpf wpf

Render a "not visible" WPF controls to an bitmap image


New elements haven't had their layout performed. You need to call Measure and Arrange on the control before you render it.

Canvas c = new Canvas();Rectangle r = new Rectangle{    Fill = Brushes.Orange,    Width = 200,    Height = 100};Ellipse e = new Ellipse{    Fill = Brushes.DodgerBlue,    Width = 100,    Height = 100};Canvas.SetLeft(e, 150);c.Children.Add(r);c.Children.Add(e);var size = new Size(250,100);c.Measure(size);c.Arrange(new Rect(size));RenderTargetBitmap bmp = new RenderTargetBitmap(250, 100, 96, 96, PixelFormats.Pbgra32);bmp.Render(c);PngBitmapEncoder enc = new PngBitmapEncoder();enc.Frames.Add(BitmapFrame.Create(bmp));using(var s = File.OpenWrite("image.png"))    enc.Save(s);