antwankakki / FabricView

A new canvas drawing library for Android. Aims to be the Fabric.js for Android. Supports text, images, and hand/stylus drawing input. The library has a website and API docs, check it out
http://antwankakki.github.io/FabricView/
Apache License 2.0
1.04k stars 184 forks source link

Undo, Redo #17

Closed lanrehnics closed 7 years ago

lanrehnics commented 7 years ago

Please how do one undo and redo.

vbnn20 commented 7 years ago
package hk.test.testrx;

import android.content.Context;
import android.util.AttributeSet;

import com.agsw.FabricView.DrawableObjects.CDrawable;
import com.agsw.FabricView.FabricView;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * Created by user on 18/10/2016.
 */
public class DrawView extends FabricView {
    private ArrayList<CDrawable> undonePaths = new ArrayList<CDrawable>();

    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void undo(){
        if (getDrawableList().size() > 0) {
            undonePaths.add(getDrawableList()
                    .remove(getDrawableList().size() - 1));
            this.invalidate();
        }
    }

    public void redo(){
        if (undonePaths.size()>0) {
            getDrawableList().add(undonePaths.remove(undonePaths.size() - 1));
            this.invalidate();
        }
    }

    public ArrayList<CDrawable> getDrawableList() {
        try {
            Field field = FabricView.class.getDeclaredField("mDrawableList");
            field.setAccessible(true);
            Object value = field.get(this);
            field.setAccessible(false);

            if (value == null) {
                return null;
            } else if (ArrayList.class.isAssignableFrom(value.getClass())) {
                return (ArrayList) value;
            }
            throw new RuntimeException("Wrong value");
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void cleanPage() {
        super.cleanPage();
        while(!this.undonePaths.isEmpty()) {
            this.undonePaths.remove(0);
        }
        this.invalidate();
    }

}
emmanuelproulx commented 7 years ago

This has been implemented in the latest version of the code. Now all you have to do is call FabricView.undo() or FabricView.redo().