C# Draw On Panel

I encountered an interesting problem on stackoverflow where someone needed to do continuous line drawing on a panel. For this I simply kept track of the last point and drew a round ended line between last point and current point in the mousemove event. Drawing only starts when the mouse is clicked down and stops when the mouse button is released. The tricky part was that if you drew directly on the panel the drawing would be lost when the panel paint event was called like in a window minimise/maximise. To solve this problem I basically did all the drawing on a bitmap object (where I wouldn't have to worry about the paint event). The bitmap was then drawn on the panel everytime a point was added or the panel was repainted.

namespace Drawing
{
    public partial class Form1 : Form
    {
        bool draw = false;

        int pX = -1;
        int pY = -1;

        Bitmap drawing;

        public Form1()
        {
            InitializeComponent();

            drawing = new Bitmap(panel1.Width, panel1.Height, panel1.CreateGraphics());
            Graphics.FromImage(drawing).Clear(Color.White);
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (draw)
            {
                Graphics panel = Graphics.FromImage(drawing);

                Pen pen = new Pen(Color.Black, 14);

                pen.EndCap = LineCap.Round;
                pen.StartCap = LineCap.Round;

                panel.DrawLine(pen, pX, pY, e.X, e.Y);

                panel1.CreateGraphics().DrawImageUnscaled(drawing, new Point(0, 0));
            }

            pX = e.X;
            pY = e.Y;
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            draw = true;

            pX = e.X;
            pY = e.Y;
        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            draw = false;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawImageUnscaled(drawing, new Point(0, 0));
        }
    }
}

2 comments: