截取控件并保存为图片(绝对好用)

        /// <summary>
        /// 截取保存控件为PNG
        /// </summary>
        /// <param name="panel">你要截取的控件名</param>
        public void ScreenShotSave(FrameworkElement panel)
        {
            string rootFolder = Directory.GetCurrentDirectory() + @"\Paper\";
            var dlg = new SaveFileDialog
            {
                FileName = rootFolder + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-ff") + ".png"
            };
            if (!Directory.Exists(rootFolder))
                Directory.CreateDirectory(rootFolder);

            using (var file = new FileStream(dlg.FileName, FileMode.Create, FileAccess.Write))
            {
                int marg = int.Parse(panel.Margin.Left.ToString(CultureInfo.InvariantCulture));
                var rtb = new RenderTargetBitmap((int)panel.ActualWidth - marg,
                                (int)panel.ActualHeight - marg, 0, 0, PixelFormats.Default);
                rtb.Render(panel);
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                encoder.Save(file);
                file.Close();
            }
        }

 

posted @ 2014-08-29 13:48  LEE ICE  阅读(964)  评论(0编辑  收藏  举报