最近需要用到这个功能,搜了一下不少代码有问题 ,找到一个效果比较好的,支持多级子元素 记一下.
private void button_save_window_Click(object sender, RoutedEventArgs e)
{ util.SaveWindow(this,,"d:\\window.png");
} private void button_save_canvas_Click(object sender, RoutedEventArgs e)
{ util.SaveCanvas(this,this.canvas1, , "d:\\canvas.png");
}
} public static class util
{
public static void SaveWindow(Window window, int dpi, string filename)
{ var rtb = new RenderTargetBitmap(
(int)window.Width, //width
(int)window.Width, //height
dpi, //dpi x
dpi, //dpi y
PixelFormats.Pbgra32 // pixelformat
);
rtb.Render(window); SaveRTBAsPNG(rtb, filename); } public static void SaveCanvas(Window window, Canvas canvas, int dpi, string filename)
{
Size size = new Size(window.Width , window.Height );
canvas.Measure(size);
//canvas.Arrange(new Rect(size)); var rtb = new RenderTargetBitmap(
(int)window.Width, //width
(int)window.Height, //height
dpi, //dpi x
dpi, //dpi y
PixelFormats.Pbgra32 // pixelformat
);
rtb.Render(canvas); SaveRTBAsPNG(rtb, filename);
} private static void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
{
var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp)); using (var stm = System.IO.File.Create(filename))
{
enc.Save(stm);
}
}