Android FingerPaint Undo/Redo implementation

后端 未结 5 1279
庸人自扰
庸人自扰 2020-12-28 21:48

I\'m working on a test project which is something similar to FingerPaint example in Android SDK Demos. I was trying to implement undo/redo functionality in my p

5条回答
  •  长情又很酷
    2020-12-28 22:17

    One way to implement a do/redo functionality is to encapsulate a method call and all info needed for the call in an object so that you can store it and call it later - the Command Pattern.

    In this pattern, each action has its own object: DrawCircleCommand, DrawPathCommand, FillColorCommand, etc. In each object the draw() method is implemented in a unique way but is always called as draw(Canvas canvas) which allows the CommandManager to iterate through the commands. To undo you iterate over the objects calling the undo() method;

    Each command object implements an Interface

    public interface IDrawCommand {  
      public void draw(Canvas canvas);  
      public void undo();  
    }  
    

    An object would look like:

    public class DrawPathCommand implements IDrawCommand{  
      public Path path;  
      public Paint paint;  
    
      public void setPath(path){
        this.path = path
      }
    
      public void draw(Canvas canvas) {  
        canvas.drawPath( path, paint );  
      }  
    
      public void undo() {  
       //some  action to remove the path
     }  
    

    }

    Your commands are added to the CommandManager:

    mCommandManager.addCommand(IDrawCommand command)
    

    and to undo a command you just call:

    mCommandManager.undo();
    

    The CommandManager stores the commands in a data structure e.g. list that allows it to iterative over the command objects.

    You can find a complete tutorial here on how to implement the Command Pattern with do/undo for Canvas drawing on Android.

    Here is a another tutorial on how implement the Command Pattern in Java;

提交回复
热议问题