Eric Lopez-Reyes
Eric Lopez-Reyes

Reputation: 97

Clearing lines drawn on picture box in c# windows form

I have a c# windows form program where the user can draw lines with a mouse on an image in the picture box. The graphics are meant to be created by the pictureBox1_Paint method. How can I erase the drawn lines and keep the image in tact?

Defined default image here:

public lineTest()
{
 InitializeComponent();
 defaultImage = pictureBox1.Image;
 }    

Drew lines like this:

 private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            lines.Push(new Line { Start = e.Location });
    }
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (lines.Count > 0 && e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            lines.Peek().End = e.Location;
            pictureBox1.Invalidate();
        }
    }

private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        foreach (var line in lines)
        {
            Pen magenta = new Pen(Color.Magenta, 5);

            e.Graphics.DrawLine(magenta, line.Start, line.End);
        }
    }

And tried erasing lines with:

private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = defaultImage;
        pictureBox1.Invalidate();
    }

and nothing appears to happen.

Upvotes: 0

Views: 1056

Answers (1)

Handbag Crab
Handbag Crab

Reputation: 1538

Paint is called every time you invalidate the control so your lines are re-drawn every time. In your button1_Click event handler add this line:

lines.Clear();

before you call pictureBox1.Invalidate();

That will stop the lines being re-drawn when the paint event next fires.

Upvotes: 2

Related Questions