Search code examples
c#.netdrawingsystem.drawing

Undo button for System.Drawing?


I am making a image editor kinda for own enjoyment and was wondering how could I make a undo button to undo the last paints I did? I want to know how I would about this, a tutorial or sample code would be nice or at least something pointing me in the right direction.

Thanks!


Solution

  • heh undo in really non that hard as it sounds. The magic here that you should record each action as object which is painted in a list or queue, f.ex, user draws a line, so your record could look like x,y of start poing, and x,y of end point or object it self which have method Draw(), so what undo will do just remove that object.

    in code that could look something like this:

    interface IDrawObject
    {
         public void Draw();
    }
    
    class Line : IDrawObject
    {
        private Point _startP;
        private Point _endP;
    
        public Line(Point startPoint; Poing endPoint)
        {
            _startP = startPoint;
            _endP = endPoint;
        }
    
        public void Draw()
        {
            //* call some generic draw processor to perform the action with your given parameters.
        }
    }
    
    class Rectangle : IDrawObject
    {
        //* your code.
        public void Draw()
        {
             //* call some generic draw processor to perform the action with your given parameters.
        }
    }
    
    //* then in your code, you could have something like this.
    List<IDrawObject> myObjectsINeedToDraw = new List<IDrawObject>();
    myObjectsINeedToDraw.Add(new Line(new Point(0, 0), new Point(10, 10));
    
    foreach(IDrawObject objectToDraw in myObjectsINeedToDraw)
    {
        //* will draw your object.
        objectToDraw.Draw();
    }
    
    //* in this way you will have unlimited history of your objects, and you will always can remove object from that list.