Mohammad Jafar Mashhadi
Mohammad Jafar Mashhadi

Reputation: 4251

Clear drawn graphics on a picturebox without clearing original picture

In a geographical software written in C#, a PictureBox is used to show GIS map that is saved as a png file in a temporary directory. There is some geometric shapes we need to be drawn on map. We used System.Drawing methods to perform this action.

Sometimes we need to change some properties these shapes or delete them, we need to remove the shapes without making beneath them black. Drawing them again with Color.Transparent obviously doesn't work, using Graphics#Clear(Color.Transparent) doesn't work too for the same reason.

We even tried using another picture box with transparent background that is used only for purpose of drawing shapes on; so that when we use Graphics#Clear(Color.Transparent) map container remains untouched. Sounded like a perfect idea at first, but because i don't know how and why it makes map container PictureBox invisible and map viewer panel is totally black, this idea failed too.

MapViewerForm
    |-- Toolbar
    |-- StatusBar
    |-- MapViewer Panel (Provides scrollbars)
            |-- MapContainer Pictutebox
            |-- Shapes drawing canvas PictureBbox (The same size and location as map container, only difference is z-order)

I prefer to use the two PictureBoxes and making 'layers' idea, i think it's less unprofessional than the other idea (I am actually a java developer and this is a C# project!), I think there should be something like java's JLayeredPane in C# to adjust z-order of those two picture boxes and omit black screen bug, But if there is a solution to draw shapes on map container itself and then clear them without losing portions of maps lying behind them i'd appreciate that answer too.

P.S: If we load map picture from file and store it in a Bitmap or Image private field and when we need to clear drawings, load image from that field with a piece of code like picMapArea.Image = MapViewer.getInstance().getMapImage(); (Note: MapViewer is a singleton class) the painted shapes will be gone but it's obviously not anything like a "good idea" because of poor performance and lagging.

Thanks in advance.

Upvotes: 1

Views: 7881

Answers (2)

Hans Passant
Hans Passant

Reputation: 941455

Simply draw the shapes in an event handler for the picturebox Paint event.

To restore the view, all you have to do is call the picturebox Invalidate() method, so it repaints the Image, and not draw anything in your Paint event handler.

Upvotes: 2

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

Just use an additional Bitmap:

Bitmap original = LoadBitmap(...);





Bitmap copy = new Bitmap(original);

Graphics graph = Graphics.FromImage(copy);

// draw some extra


PictureBox1.Image = copy;

Upvotes: 2

Related Questions