0

I have a custom control that displays an image. I'm using a custom control because I've implemented zooming functionality and scrollbars.

I'm draw a rectangle on the image by doing:

if (drawRect)
{
    var g = Graphics.FromImage(Image);
    g.DrawRectangle(Pens.Red, rect);
}

The drawing of the rectangle is toggled by a button. However, when I toggle off, the rectangle it's still being drawn on the image.

I'm assuming that once something is drawn on the image's surface, it stays there.

Is there a way to "undraw" something or do I need to implement a second "transparent" image that will act as an overlay?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • If you drew a transparent rectangle on top of the red rectangle, you'd still see the red rectangle underneath. – Adam V Jun 16 '16 at 18:00
  • @AdamV I would then draw the red rectangle on the transparent image so will act as an overlay. – Ivan-Mark Debono Jun 16 '16 at 18:01
  • Whenever you draw to a graphics context, everything is merged, so to speak, so to remove the rectangle, you will need to redraw the entire surface, minus the rectangle. Take a look at the Invalidate, Update and Refresh methods of your control. – Matthew Layton Jun 16 '16 at 18:05
  • 1
    You have drawn into the bitmap, so you have changed the pixels. You can combine displaying a bitmap as background in most controls with drawing onto the surface in the paint event. This is the way to get rid of stuff drawn. - See [here for examples of both](http://stackoverflow.com/questions/27337825/picturebox-paintevent-with-other-method/27341797?s=3|0.3441#27341797). What control are you drawing on? Make sure to set its Double-Buffered property to true! – TaW Jun 16 '16 at 18:05
  • As a side note - constant redrawing may result in poor graphics performance (tearing, artifacts etc), so you might want to consider buffered drawing (draw everything to a bitmap in memory, and then flush the bitmap to the screen in one hit). Also, look at the SetStyle method and the ControlStyles.ResizeRedraw enum – Matthew Layton Jun 16 '16 at 18:08
  • Perhaps [ControlPaint.DrawReversibleFrame Method](https://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint.drawreversibleframe(v=vs.110).aspx) will meet your needs. As it draws directly to the desktop window, any refreshes of the region will cause it to disappear. – TnTinMn Jun 16 '16 at 18:37

0 Answers0