WPF 实现指定UI控件截图

时间:2021-12-05 15:24:03
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);
            }
        }