malaka
malaka

Reputation: 95

Undo and redo canvas

I am trying to implement undo and redo in my application. I was reading other questions and forums but the code is not working for me. I post here only the relevant code for easier reading because I draw different shapes. For redo and undo I have two buttons in another activity and I call the functions redo or undo in the onclicklistener of each button.

private void setupDrawing(){
    drawPath=new Path();

    //Set up paint

    paths.add(drawPaint);
}

public boolean onTouchEvent(MotionEvent event){
    tX=event.getX();
    tY=event.getY();
    switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:

            //Action move down

        break;
        case MotionEvent.ACTION_MOVE:

            //Action move

        break;
        case MotionEvent.ACTION_UP:
            drawCanvas.drawCircle(x, y, radius, drawPaint); //Example of drawing object
            drawPath = new Path();
            paths.add(drawPath);
        break;
        default:
            return false;
    }
    invalidate();
    return true;
}    

public void undo(){
    if(paths.size()>0){
        undonePaths.add(paths.remove(paths.size()-1));
        invalidate();
    }
    if(undo==true){
        undo=false;
    }else{
        undo=true;
    }
}

public void redo(){
    if(undonePaths.size()>0){
        paths.add(undonePaths.remove(undonePaths.size()-1));
        invalidate();
    }
    if(redo==true){
        redo=false;
    }else{
        redo=true;
    }
}

Upvotes: 2

Views: 485

Answers (1)

malaka
malaka

Reputation: 95

I found what was wrong with my code. I was drawing on canvas and I need to add the shapes to the path. I leave here the code for that if someone need it.

protected void onDraw(Canvas canvas){
    for(Path p : paths){
        canvas.drawPath(p, drawPaint);
    }
    canvas.drawPath(drawPath, drawPaint);
}

//Here all the code for the Motion Event. I will show only the Action Up.

case MotionEvent.ACTION_UP:
        drawPath.addCircle(x, y, radius, Path.Direction.CCW); //Example of drawing object
        paths.add(drawPath);
        drawPath = new Path();
    break;

Upvotes: 1

Related Questions