I need to save visible content of Canvas
as PNG.
I have the folowing method that takes actual size of Canvas
and save it as image.
private void SavePng()
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(this.CanvasMain);
//I also tried this
/*Rect bounds = new Rect(
new Point(0, 0),
new Point(this.CanvasMain.ActualWidth, this.CanvasMain.ActualHeight)
);*/
double dpi = 96d;
RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(this.CanvasMain);
dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}
rtb.Render(dv);
BitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
pngEncoder.Save(ms);
ms.Close();
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "Image (.png)|*.png";
string filename = "";
if (dlg.ShowDialog() == true)
filename = dlg.FileName;
System.IO.File.WriteAllBytes(filename, ms.ToArray());
}
catch (ArgumentException err)
{
MessageBox.Show("Wrong path!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
But if I have an object out of bounds of the window, I will get something like this:
How do I get only the visible part of the Canvas
that is within the bounds of the window?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…