Created
June 27, 2020 04:15
-
-
Save SnowyPainter/643caaeab72355549b77160432cd6354 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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