Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // I pass in 320x150 or 434x210 or 558x270 depending on the scale.
- public static MemoryStream ToPng(
- this FrameworkElement frameworkElement,
- double width,
- double height)
- {
- BitmapSource bitmapSource = ToBitmapSource(frameworkElement, width, height);
- PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
- pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource));
- MemoryStream memoryStream = new MemoryStream();
- pngBitmapEncoder.Save(memoryStream);
- memoryStream.Position = 0;
- return memoryStream;
- }
- public static BitmapSource ToBitmapSource(
- this FrameworkElement frameworkElement,
- double width,
- double height)
- {
- Size renderingSize = new Size(width, height);
- frameworkElement.Measure(renderingSize);
- Rect renderingRectangle = new Rect(new Point(0, 0), renderingSize);
- frameworkElement.Arrange(renderingRectangle);
- frameworkElement.UpdateLayout();
- Rect bounds = VisualTreeHelper.GetDescendantBounds(frameworkElement);
- RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
- (int)frameworkElement.ActualWidth,
- (int)frameworkElement.ActualHeight,
- 96,
- 96,
- PixelFormats.Pbgra32);
- DrawingVisual drawingVisual = new DrawingVisual();
- using (DrawingContext drawingContext = drawingVisual.RenderOpen())
- {
- VisualBrush visualBrush = new VisualBrush(frameworkElement);
- drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(), bounds.Size));
- }
- renderBitmap.Render(drawingVisual);
- return renderBitmap;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement