Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. // I pass in 320x150 or 434x210 or 558x270 depending on the scale.
  2. public static MemoryStream ToPng(
  3. this FrameworkElement frameworkElement,
  4. double width,
  5. double height)
  6. {
  7. BitmapSource bitmapSource = ToBitmapSource(frameworkElement, width, height);
  8.  
  9. PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
  10. pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource));
  11.  
  12. MemoryStream memoryStream = new MemoryStream();
  13. pngBitmapEncoder.Save(memoryStream);
  14.  
  15. memoryStream.Position = 0;
  16.  
  17. return memoryStream;
  18. }
  19.  
  20. public static BitmapSource ToBitmapSource(
  21. this FrameworkElement frameworkElement,
  22. double width,
  23. double height)
  24. {
  25. Size renderingSize = new Size(width, height);
  26. frameworkElement.Measure(renderingSize);
  27. Rect renderingRectangle = new Rect(new Point(0, 0), renderingSize);
  28. frameworkElement.Arrange(renderingRectangle);
  29. frameworkElement.UpdateLayout();
  30.  
  31. Rect bounds = VisualTreeHelper.GetDescendantBounds(frameworkElement);
  32. RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
  33. (int)frameworkElement.ActualWidth,
  34. (int)frameworkElement.ActualHeight,
  35. 96,
  36. 96,
  37. PixelFormats.Pbgra32);
  38.  
  39. DrawingVisual drawingVisual = new DrawingVisual();
  40.  
  41. using (DrawingContext drawingContext = drawingVisual.RenderOpen())
  42. {
  43. VisualBrush visualBrush = new VisualBrush(frameworkElement);
  44. drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(), bounds.Size));
  45. }
  46.  
  47. renderBitmap.Render(drawingVisual);
  48.  
  49. return renderBitmap;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement