我制作了一个绘图程序,并在面板上绘制了绘图内容(来自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;
}
答案 0 :(得分:2)
这是一个最小的涂鸦程序,可以让你绘制持久的行:
List<Point> curPoints = new List<Point>();
List<List<Point>> allPoints = new List<List<Point>>();
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<Point> 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);
}
添加您的保存代码,如果您遇到问题,请说明..
更新:我添加了两个代码片段,用于执行保存和(无限制)撤消..
答案 1 :(得分:0)
我会跳过使用面板,它不像ImageBox那样设计用于图形 - 转到那个然后你可以轻松保存内容。
<强>更新强> 图片框。我暂时没有使用WinForms:D
答案 2 :(得分:0)
在GitHub上查看此代码ScreenToGif。
文件夹GifRecorder\Controls\FreeDrawPanel.cs
中有一个实现,它支持方形和圆形画笔,橡皮擦并保存输出图像。