0

我正在尝试将面板上的图像保存到 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();
    }

最后结果

这是我画的

我画的

这就是节省

保存了什么

4

1 回答 1

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);
        }                       
    }
}
于 2013-02-03T17:51:42.657 回答