如何使用图形清除图片框中绘制的矩形?

时间:2014-09-15 10:19:40

标签: c# winforms

我在图片框中绘制了12个带有一些坐标的矩形,现在我想在图片框中清除绘制的矩形,然后在同一个图片框中加载下一个图像。 对于绘制矩形,我使用以下代码,

>  g.DrawRectangle(pen1, rect);

其中g是Graphics,pen1 = new System.Drawing.Pen(Color.Red,2F);和rect是带有x,y,宽度和高度坐标的矩形。

而且我希望我绘制的图形能够调整大小,因为我使用PosSizableRect Enum和picturebox Mousedown,mousemove和Mouseleave事件,并且我的矩形光标被更改,以便用户可以调整绘制的矩形坐标的大小。

如何在同一PictureBox中加载下一张图像之前清除PictureBox中绘制的矩形? 我尝试了以下解决方案,但对我来说没有任何作用。 g.Clear(Color.Red); ,this.Invalidate(); ,pictureBox1.Refresh(); pictureBox1.Image = NULL;和img.Dispose();

请指导我!!!我该如何进一步继续?

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

您可以通过以下代码将图片框留空(完全删除):

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

答案 2 :(得分:0)

除非您实际存储使用的图像数据,否则无法实现。除非你想用ex填充图片框。白色。我为你写了一个简单的课程来实现这个目标。

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;
            }
        }
    }
相关问题