Search code examples
c#winformsgraphicsdraw

Graphics.Clear a given image? C# Winforms


i have code this code to draw an image on a Picture-box in my Winforms application, I was wondering if there was a way to clear an individual image instead of clearing everything.

public void DrawImage(Image img, Point pos)
    {
        if (GraphicsRenderer!=null)
        {
            GraphicsRenderer.DrawImage(img, pos);
        }
    }
DrawImage(Image.FromFile("image.png"), new Point(0, 0));

// then this to draw a rectangle
public void DrawRectangle(Rectangle rect, Pen pen)
    {
        if (GraphicsRenderer == null)
            GraphicsRenderer = Renderer.CreateGraphics();

        GraphicsRenderer.DrawRectangle(pen, rect);
    }
DrawRectangle(new Rectangle(new Point(0, 0), new Size(40, 40)), Pens.Red);

// now how do i clear only the image?

Any help or insight is appreciated!


Solution

  • You can't. You'll have to redraw the entire picture, without your image.png. Your graphics calls are ultimately drawing to an underlying graphics buffer (think: raw pixel data). When you draw on that underlying graphics buffer, you overwrite what was previously there, and there is no such thing as an undo operation.