我正在尝试将我的面板上的图像保存到BMP,每当它保存时,只有一个空白图像。
绘图代码
private void DrawingPanel_MouseMove(object sender, MouseEventArgs e)
{
OldPoint = NewPoint;
NewPoint = new Point(e.X, e.Y);
if (e.Button == MouseButtons.Left)
{
Brush brush = new SolidBrush(Color.Red);
Pen pen = new Pen(brush, 1);
DrawingPanel.CreateGraphics().DrawLine(pen, OldPoint, NewPoint);
}
}
保存代码
void SaveBMP(string location)
{
Bitmap bmp = new Bitmap((int)DrawingPanel.Width, (int)DrawingPanel.Height);
DrawingPanel.DrawToBitmap(bmp, new Rectangle(0, 0, DrawingPanel.Width, DrawingPanel.Height));
FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate);
bmp.Save(saveStream, ImageFormat.Bmp);
saveStream.Flush();
saveStream.Close();
}
最终结果
这就是我画的
这就是保存
答案 0 :(得分:2)
您必须更改代码才能覆盖OnPaint方法。这是自定义控件外观时遵循的默认模式。
您的特定代码无法工作的原因是DrawToBitmap必须在调用时重新绘制整个控件。在这种情况下,该方法不知道您的控件的自定义绘图。
这是一个有效的例子:
public partial class DrawingPanel : Panel
{
private List<Point> drawnPoints;
public DrawingPanel()
{
InitializeComponent();
drawnPoints = new List<Point>();
// Double buffering is needed for drawing this smoothly,
// else we'll experience flickering
// since we call invalidate for the whole control.
this.DoubleBuffered = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// NOTE: You would want to optimize the object allocations,
// e.g. creating the brush and pen in the constructor
using (Brush brush = new SolidBrush(Color.Red))
{
using (Pen pen = new Pen(brush, 1))
{
// Redraw the stuff:
for (int i = 1; i < drawnPoints.Count; i++)
{
e.Graphics.DrawLine(pen, drawnPoints[i - 1], drawnPoints[i]);
}
}
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
// Just saving the painted data here:
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
drawnPoints.Add(e.Location);
this.Invalidate();
}
}
public void SaveBitmap(string location)
{
Bitmap bmp = new Bitmap((int)Width, (int)Height);
DrawToBitmap(bmp, new Rectangle(0, 0, Width, Height));
using (FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate))
{
bmp.Save(saveStream, ImageFormat.Bmp);
}
}
}