C# 如何使用图形清除picturebox中绘制的矩形?

C# 如何使用图形清除picturebox中绘制的矩形?,c#,winforms,C#,Winforms,我在picturebox中绘制了12个带有坐标的矩形,现在我想在将下一幅图像加载到同一个picturebox之前清除picturebox中绘制的矩形。 对于绘制矩形,我使用了以下代码 > g.DrawRectangle(pen1, rect); 其中g是图形,pen1=新系统.Drawing.Pen(Color.Red,2F);rect是带有x,y,宽度和高度坐标的矩形 我还希望我绘制的图形能够调整大小,因为我在picturebox Mousedown、mousemove和Mousel

我在picturebox中绘制了12个带有坐标的矩形,现在我想在将下一幅图像加载到同一个picturebox之前清除picturebox中绘制的矩形。 对于绘制矩形,我使用了以下代码

>  g.DrawRectangle(pen1, rect);
其中g是图形,pen1=新系统.Drawing.Pen(Color.Red,2F);rect是带有x,y,宽度和高度坐标的矩形

我还希望我绘制的图形能够调整大小,因为我在picturebox Mousedown、mousemove和Mouseleave事件中使用了PosSizableRect枚举,并且我的矩形光标被更改,这样用户就可以调整绘制的矩形坐标的大小

在同一个PictureBox中加载下一个图像之前,如何清除PictureBox中绘制的矩形? 我尝试了以下解决方案,但没有任何效果。 g、 清晰(颜色为红色),这个。使()无效,pictureBox1.Refresh();pictureBox1.Image=null;和img.Dispose()


请引导我!!!如何继续?

您是打算删除已绘制的矩形以将图像恢复到原始状态,还是打算在图片上绘制一个“清晰”(即白色)的矩形

在第二种情况下,应该使用Graphics.FillRectangle


在第一种情况下,您需要保留原始图像的副本,并在希望消除已绘制的矩形时重新绘制它。

您可以通过以下代码将picturebox变为空白(完全擦除):

g.FillRectangle(Brushes.Black, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));

除非您实际存储使用的图像数据,否则无法实现这一点。除非你想在图片盒里填上前白色。我为您编写了一个简单的类来实现这一点

public class RestorablePictureBox : PictureBox
    {
        private Image _restoreImage;
        private Image _restoreBackgroundImage;

        protected override void OnPaint(PaintEventArgs pe)
        {
            if (_restoreImage != null) _restoreImage.Dispose();
            if (_restoreBackgroundImage != null) _restoreBackgroundImage.Dispose();

            _restoreImage = this.Image;
            _restoreBackgroundImage = this.BackgroundImage;

            base.OnPaint(pe);
        }

        public void Restore(bool fill = false)
        {
            if (fill)
            {
                if (_restoreImage != null) _restoreImage.Dispose();
                if (_restoreBackgroundImage != null) _restoreBackgroundImage.Dispose();

                using (var gfx = this.CreateGraphics())
                {
                    gfx.FillRectangle(Brushes.White, 0, 0, this.Width, this.Height); // Change Brushes.White to the color you want or use new SolidBrush(Color)
                }
            }
            else
            {
                if (_restoreImage != null) this.Image = _restoreImage;
                if (_restoreBackgroundImage != null) this.BackgroundImage = _restoreBackgroundImage;
            }
        }
    }

如何在我的代码中使用这个类,实际上我的代码中有一个清除按钮,当我单击按钮矩形应该从我的picturebox中清除时,我在代码中复制了这个类。我是C#.net的初学者,所以请指导我,如何在我的代码中使用此类方法来清除picturebox中的矩形??将您的picturebox更改为此picturebox。您可以从工具箱中拖动它(在构建一次之后),或者像“var restorePic=new RestorablePictureBox();”那样创建它,这取决于您如何绘制矩形。如果使用g=pictureBox1.CreateGraphics();然后是一个简单的例子:this.Invalidate();很好用。如果您的pictureBox1中有一个图像,例如pictureBox1.image=img,并且您在img上绘制,那么您必须清除img并使其无效。显示一些代码