Winform将控件保存为图片比较简单,因为Control类本身就有DrawToBitmap方法,可以将控件本身输出到图片中。
此外,还可以通过Graphics类的CopyFromScreen方法将屏幕的指定区域拷贝到指定位图中,只是这种方式对窗口类比较适用,而且会保留窗口的阴影部分,因此对于截取控件图片不是很完美。
1、DrawToBitmap
/// <summary> /// 保存控件到图片 /// </summary> /// <param name="control">控件对象</param> /// <param name="fileName">文件名</param> public static void SaveControlToPng(Control control, string fileName) { var width = control.Size.Width; var height = control.Size.Height; using (var bmp = new Bitmap(width, height)) { control.DrawToBitmap(bmp, new Rectangle(0, 0, width, height)); bmp.Save(fileName, ImageFormat.Png); } }
2、CopyFromScreen
/// <summary> /// 保存屏幕区域到图片 /// </summary> /// <param name="x">屏幕x坐标</param> /// <param name="y">屏幕y坐标</param> /// <param name="width">宽度</param> /// <param name="height">高度</param> /// <param name="fileName">文件名</param> public static void SaveScreenToPng(int x, int y, int width, int height, string fileName) { using (var bmp = new Bitmap(width, height)) using (var graphics = Graphics.FromImage(bmp)) { graphics.CompositingQuality = CompositingQuality.HighQuality; //质量设为最高 graphics.CopyFromScreen(x, y, 0, 0, new Size(width, height)); //保存整个屏幕区域 bmp.Save(fileName, ImageFormat.Png); } }标签:control,控件,保存,height,width,bmp,var,Winform From: https://www.cnblogs.com/xhubobo/p/16947335.html