I want to develope a .NET application with WPF.
In the end there should be a Viewbox or something similar, this Viewbox should contain a canvas and in this canvas there could be various things like filled rectangles, ellipses etc. ( like a drawing application eg. paint).
Now I want to implement the functionallity to save the content of the Canvas to a PNG. I tried rendering the Canvas to a RenderTargetBitmap and then saving it.
The problem here is that I am not able to set specific coordinates, the only thing I can set is the Size (Canvas width & height) of the RenderTargetBitmap, but it will start rendering the Size starting from (0|0) where my Canvas element starts somewhere else. Is there some work arround for that??
The next Problem is, there should be the posibilty to add pictures as sub-element of the root-Canvas, but how could I care about quality and that everything in the Viewbox is printed?
Thank you very much!
------ EDIT ------
I think I've got a Solution:
void SaveUsingEncoder(Canvas myCanvas, string fileName)
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
RenderTargetBitmap bitmap = new RenderTargetBitmap(
(int)myCanvas.ActualWidth,
(int)myCanvas.ActualHeight,
96,
96,
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);
}
}
This saves the complete canvas for me
at specific position -
I think in your case use Margins.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.