猿问

在c# windows窗体中清除画在图片框上的线条

我有 ac# windows 窗体程序,用户可以在其中用鼠标在图片框中的图像上画线。图形是由 pictureBox1_Paint 方法创建的。如何擦除绘制的线条并保持图像完整?


在这里定义的默认图像:


public lineTest()

{

 InitializeComponent();

 defaultImage = pictureBox1.Image;

 }    

画出这样的线条:


 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);

        }

    }

并尝试使用以下方法擦除线条:


private void button1_Click(object sender, EventArgs e)

    {

        pictureBox1.Image = defaultImage;

        pictureBox1.Invalidate();

    }

似乎什么也没发生。


慕田峪7331174
浏览 878回答 1
1回答

四季花海

每次使控件无效时都会调用 Paint,因此每次都会重新绘制线条。在您的button1_Click事件处理程序中添加以下行:lines.Clear();在你打电话之前 pictureBox1.Invalidate();这将在下次触发绘制事件时停止重新绘制线条。
随时随地看视频慕课网APP
我要回答