Delete rectangle using .NET?
Solution 1
No, you cannot "delete" something that's already been drawn. You can overwrite it with something else, but drawing with Graphics
objects is like painting in real-life: once the paint is dry, you can only paint over it with another colour, you can't "erase" it.
You probably shouldn't be drawing things in response to a MouseClick, either. It's best to only draw things in response to a Paint
event. What I would do in this situation is add a Rectangle
structure to a list on the MouseClick and then call panel1.Invalidate()
to ask it to redraw itself. Then in the Paint
event for the panel, do the drawing there.
This will kill two birds with one stone, because you will be able to "erase" thing by simply removing them from the list of stuff to draw.
Solution 2
This is usually done by maintaining a collection of objects you want drawn. The mouse click should update this collection and then tell the window (or the affect region) to refresh. This has the enormous advantage of preserving whatever you've drawn if the window is moved off-screen, hidden behind other windows, minimized, etc.
For a rudimentary solution, create a hierarchy of drawable shape types derived from a common abstract Shape class, and use, e.g., a List for the collection. The base Shape class will have an abstract Draw method that the derived classes override.
For a more industrial-strength solution, look around for 2-D scene graphs.
Solution 3
Also, depending on the application, you might look at using DrawReversibleFrame. You can change the rectangle location by calling the Offset method.
Solution 4
One can use Graphics.Save()
and Graphics.Restore(state)
methods for that. For example:
private void SaveRestore2(PaintEventArgs e)
{
// Translate transformation matrix.
e.Graphics.TranslateTransform(100, 0);
// Save translated graphics state.
GraphicsState transState = e.Graphics.Save();
// Reset transformation matrix to identity and fill rectangle.
e.Graphics.ResetTransform();
e.Graphics.FillRectangle(new SolidBrush(Color.Red), 0, 0, 100, 100);
// Restore graphics state to translated state and fill second
// rectangle.
e.Graphics.Restore(transState);
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 100, 100);
}
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.restore.aspx
Dinu
Updated on June 06, 2022Comments
-
Dinu almost 2 years
Can I delete the old rectangle which I have drawn and draw a new rectangle?
private void panel1_MouseClick(object sender, MouseEventArgs e) { Graphics g = this.panel1.CreateGraphics(); Pen pen = new Pen(Color.Black, 2); g.DrawRectangle(pen, 100,100, 100, 200); g.dispose(); }
-
Admin over 13 yearsYes, if you want to remove the rectangle, just dispose the controls(either the Rectangle or the ShapeContainer in whole), no painting, no hassle!!!