Hello Devels,
I want to save the Content of a WPF Canvas (which is in a ScrollViewer, so not all Content is visible) to a png. With the following code I get it working.
void SaveUsingEncoder(Canvas myCanvas, string fileName, int dpi) { PngBitmapEncoder encoder = new PngBitmapEncoder(); RenderTargetBitmap bitmap = new RenderTargetBitmap( (int)myCanvas.ActualWidth*(int)(dpi/96.0), (int)myCanvas.ActualHeight*(int)(dpi/96.0), dpi, dpi, PixelFormats.Pbgra32); Rect bounds = VisualTreeHelper.GetDescendantBounds(myCanvas); Console.WriteLine(bounds.X + "|" + bounds.Y + " " + bounds.Width + "|" + bounds.Height); DrawingVisual dv = new DrawingVisual(); using (DrawingContext ctx = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(myCanvas); ctx.DrawRectangle(vb, null, new Rect(bounds.Location, bounds.Size)); } bitmap.Render(dv); BitmapFrame frame = BitmapFrame.Create(bitmap); encoder.Frames.Add(frame); using (var stream = File.Create(fileName)) { encoder.Save(stream); } }
But there is the Issue of Quality: I want to put pictures inside of the Canvas Element, but saving the Canvas is more like making a screenshot with a specific resulution. Are there any better ways to do this?
At the end my application should be able to act like a little paint clone, you can drop pictures into the canvas where you can zoom in/out and then save it to png.