Skip to content

Instantly share code, notes, and snippets.

@SnowyPainter
Created June 27, 2020 04:15
Show Gist options
  • Save SnowyPainter/643caaeab72355549b77160432cd6354 to your computer and use it in GitHub Desktop.
Save SnowyPainter/643caaeab72355549b77160432cd6354 to your computer and use it in GitHub Desktop.
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace wpf_control_to_image.Extensions
{
public static class UIElementExtension
{
public static RenderTargetBitmap ToBitmap(this FrameworkElement element)
{
Rect emptyBox = VisualTreeHelper.GetDescendantBounds(element);
DrawingVisual visualDraw = new DrawingVisual();
using (DrawingContext ctx = visualDraw.RenderOpen())
{
ctx.DrawRectangle(new VisualBrush(element), null, new Rect(emptyBox.Size));
}
//(int)DrawCanvas.ActualWidth
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Default);
renderTargetBitmap.Render(visualDraw);
return renderTargetBitmap;
}
}
public static class BitmapExtension
{
public static PngBitmapEncoder ToPng(this RenderTargetBitmap bitmap)
{
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(bitmap));
return pngImage;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment