代码改变世界

WPF 实现指定UI控件截图

2016-04-13 11:48  孙启亮  阅读(1840)  评论(0编辑  收藏  举报
using System.Windows.Media.Imaging;
using System.IO;

private void SaveToImage(FrameworkElement ui, string fileName, int width, int height)
        {
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d,
                PixelFormats.Pbgra32);
                bmp.Render(ui);
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(fs);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }