如何将Winforms面板的绘图内容保存到文件?

我制作了一个绘图程序,并在面板上绘制了绘图内容(来自System.Drawing)。 我现在尝试这种方法进行简单的保存,我只得到一张空白图片。

我的位图的属性.RawData为0.不知道是否重要。

当我隐藏屏幕并再次显示时,面板变为空白。

另外,当我调用面板的pnlPaint.Refresh()时,面板变为空白。 图纸丢失了。 这是一个双缓冲的东西,就像它不保留值?

private bool Save() { Bitmap bmpDrawing; Rectangle rectBounds; try { // Create bitmap for paint storage bmpDrawing = new Bitmap(pnlPaint.Width, pnlPaint.Height); // Set the bounds of the bitmap rectBounds = new Rectangle(0, 0, bmpDrawing.Width, bmpDrawing.Height); // Move drawing to bitmap pnlPaint.DrawToBitmap(bmpDrawing, rectBounds); // Save the bitmap to file bmpDrawing.Save("a.bmp", ImageFormat.Bmp); } catch (Exception e) { MessageBox.Show("Error on saving. Message: " + e.Message); } return true; } 

这是一个最小的涂鸦程序,可以让你绘制持久的行:

 List curPoints = new List(); List> allPoints = new List>(); private void pnlPaint_MouseDown(object sender, MouseEventArgs e) { if (curPoints.Count > 1) { // begin fresh line or curve curPoints.Clear(); // startpoint curPoints.Add(e.Location); } } private void pnlPaint_MouseUp(object sender, MouseEventArgs e) { if (curPoints.Count > 1) { // ToList creates a copy allPoints.Add(curPoints.ToList()); curPoints.Clear(); } } private void pnlPaint_MouseMove(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; // here we should check if the distance is more than a minimum! curPoints.Add(e.Location); // let it show pnlPaint.Invalidate(); } private void pnlPaint_Paint(object sender, PaintEventArgs e) { // here you can use DrawLines or DrawCurve // current line if (curPoints.Count > 1) e.Graphics.DrawCurve(Pens.Red, curPoints.ToArray()); // other lines or curves foreach (List points in allPoints) if (points.Count > 1) e.Graphics.DrawCurve(Pens.Red, points.ToArray()); } private void btn_undo_Click(object sender, EventArgs e) { if (allPoints.Count > 1) { allPoints.RemoveAt(allPoints.Count - 1); pnlPaint.Invalidate(); } } private void btn_save_Click(object sender, EventArgs e) { string fileName = @"d:\test.bmp"; Bitmap bmp = new Bitmap(pnlPaint.ClientSize.Width, pnlPaint.ClientSize.Width); pnlPaint.DrawToBitmap(bmp, pnlPaint.ClientRectangle); bmp.Save(fileName, ImageFormat.Bmp); } 

添加您的保存代码,如果您遇到问题,请说出来……

更新:我添加了两个执行保存和(无限制)撤消的代码片段。

我会跳过使用面板,它不像ImageBox那样设计用于图形 – 继续前进,然后你可以轻松保存内容。

更新 PictureBox。 我有一段时间没有使用过WinForms:D

在GitHub上查看此代码ScreenToGif 。

文件夹GifRecorder\Controls\FreeDrawPanel.cs有一个实现,它支持方形和圆形画笔,橡皮擦并保存输出图像。