I need to create an image control. Doing this way

public static BitmapFrame CreateControlFrame(FrameworkElement control) { var width = control.ActualWidth == 0 ? control.Width : control.ActualWidth; var height = control.ActualHeight == 0 ? control.Height : control.ActualHeight; var bmp = new RenderTargetBitmap((int)Math.Ceiling(width), (int)Math.Ceiling(height), 96, 96, PixelFormats.Pbgra32); bmp.Render(control); return BitmapFrame.Create(bmp); } 

but it only works if my control is on the form and it is visible. And I need to create an image of the control that is not on the form or it is hidden ( Visibility = Hidden/Collapsed )

Ideally, like this

 var btn = new Button(); btn.Content = "qwe"; btn.Width = 100; btn.Height = 30; WpfControlRenderer.CreateControlScreenshot(btn, "ss.png"); 

Maybe someone knows how?

  • if he is invisible, then it means that he is unrendered? How then to get an image from him? : - / - Sublihim
  • @Sublihim, and then what does a class with such a big name as RenderTargetBitmap do? - iRumba
  • @ user2455111, this is for WinForms - iRumba
  • As an option for drawing, you can not turn off the control, but hide it behind others, then it will normally render into the image. - Shakra

1 answer 1

This question has already been answered in English stackoverflow : Render a “not visible” WPF controls to an bitmap image

For control, you need to call the Measure and Arrange methods, for their layout, and then render them:

 var btn = new Button(); btn.Content = "qwe"; btn.Width = 100; btn.Height = 30; var size = new Size(250,250); btn.Measure(size); btn.Arrange(new Rect(size)); RenderTargetBitmap bmp = new RenderTargetBitmap(250, 100, 96, 96, PixelFormats.Pbgra32); bmp.Render(btn); PngBitmapEncoder enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bmp)); using(var s = File.OpenWrite("image.png")) enc.Save(s); 
  • If possible, tell me how to determine if an element is drawn (that is, not to call Measure and Arrange - iRumba
  • @iRumba can probably check the property IsLoaded msdn.microsoft.com/ru-ru/library/… - Sublihim
  • And what prevents the render before creating a control and allocate a place for it and calculate its dimensions (Measure and Arrange). Then you can check that the control is created, it means that you no longer need to resize, but this will work provided that the control has a fixed size that cannot be changed between rendering to the image. - Shakra
  • @Shakra, resize forms or the presence of splitters can break this concept, probably - Sublihim
  • @Sublihim so why add control to the form? - Shakra