/// <summary> /// Render the frameworkElement to a BitmapSource /// </summary> /// <param name="frameworkElement">FrameworkElement</param> /// <param name="size">Size, using the bound as size by default</param> /// <param name="dpiX">Horizontal DPI settings</param> /// <param name="dpiY">Vertical DPI settings</param> /// <returns>BitmapSource</returns> public static BitmapSource ToBitmapSource(this FrameworkElement frameworkElement, Size?size = null, double dpiX = 96.0, double dpiY = 96.0) { if (frameworkElement == null) { throw new ArgumentNullException(nameof(frameworkElement)); } // Make sure we have a size if (!size.HasValue) { var bounds = VisualTreeHelper.GetDescendantBounds(frameworkElement); size = bounds != Rect.Empty ? bounds.Size : new Size(16, 16); } // Create a viewbox to render the frameworkElement in the correct size var viewbox = new Viewbox { //frameworkElement to render Child = frameworkElement }; viewbox.Measure(size.Value); viewbox.Arrange(new Rect(new Point(), size.Value)); viewbox.UpdateLayout(); var renderTargetBitmap = new RenderTargetBitmap((int)(size.Value.Width * dpiX / 96.0), (int)(size.Value.Height * dpiY / 96.0), dpiX, dpiY, PixelFormats.Pbgra32); var drawingVisual = new DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) { var visualBrush = new VisualBrush(viewbox); drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(), size.Value)); } renderTargetBitmap.Render(drawingVisual); // Disassociate the frameworkElement from the viewbox viewbox.RemoveChild(frameworkElement); return(renderTargetBitmap); }