Memory drawing control (bitmap)

Can I draw a wpf control in memory (Bitmap) without drawing on the screen?
I found an example of saving in Bitmap, but it only works when the window was drawn on the screen.

BitmapImage bitmap = new BitmapImage(); RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)canvaspad.Width, (int)canvaspad.Height, 96, 96, System.Windows.Media.PixelFormats.Default); renderTarget.Render(canvaspad); 
+3
source share
1 answer

Since the control does not have a parent container, you need to call Measure and Arrange to make the correct layout. Since the layout runs asynchronously (see Notes in Measure and Arrange ), you may also need to call UpdateLayout to immediately update the layout.

 public BitmapSource RenderToBitmap(UIElement element, Size size) { element.Measure(size); element.Arrange(new Rect(size)); element.UpdateLayout(); var bitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96, 96, PixelFormats.Default); bitmap.Render(element); return bitmap; } 

If you have already set the Width and Height this element, you can use it for the size parameter:

 var grid = new Grid { Width = 200, Height = 200, Background = Brushes.Yellow }; grid.Children.Add( new Ellipse { Width = 100, Height = 100, Fill = Brushes.Blue }); var bitmap = RenderElement(grid, new Size(grid.Width, grid.Height)); 
+3
source

Source: https://habr.com/ru/post/1242176/


All Articles