ANDROID - 在画布中撤消和重做

时间:2016-03-18 10:01:09

标签: android canvas bitmap undo-redo

我在位图上画一个圆圈(在触摸上)以擦除圆圈中该区域的叠加位图。如何为此添加撤消和重做功能?

编辑:请参考Android: Undo redo in CustomView,因为它遇到了我目前面临的问题。

@Override
    protected void onDraw(Canvas canvas) {
        pcanvas.drawCircle(x, y, 10, mPaint);
        canvas.drawBitmap(bitmap, 0, 0, null);
        super.onDraw(canvas);

    }

的onTouchEvent

public boolean onTouchEvent(MotionEvent ev) 
    {
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            {

                x = (int) ev.getX();
                y = (int) ev.getY();
                invalidate();

                break;
            }

            case MotionEvent.ACTION_MOVE:
            {

               x = (int) ev.getX();
                y = (int) ev.getY();
                invalidate();
                break;

            }

            case MotionEvent.ACTION_UP:
                invalidate();
                break;

        }
        return true;
    }

1 个答案:

答案 0 :(得分:1)

如评论中所述,您可以保持堆栈跟踪xy坐标历史记录。

撤消和重做操作围绕从单独的堆栈推送和弹出。

UndoCanvas

public class UndoCanvas extends View {
    private final int MAX_STACK_SIZE = 50;
    private Stack<Pair<Float, Float>> undoStack = new Stack<>();
    private Stack<Pair<Float, Float>> redoStack = new Stack<>();

    private Bitmap originalBitmap;
    private Bitmap maskedBitmap;
    private Canvas originalCanvas;
    private Canvas maskedCanvas;
    private Paint paint;

    private float drawRadius;

    private StackListener listener;

    public UndoCanvas(Context context) {
        super(context);

        init();
    }

    public UndoCanvas(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public UndoCanvas(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
        drawRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());

        paint = new Paint();
        // paint.setColor(Color.RED);

        paint.setAlpha(0);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        paint.setAntiAlias(true);
        paint.setMaskFilter(new BlurMaskFilter(15, BlurMaskFilter.Blur.SOLID));
    }

    public void setBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            originalBitmap = bitmap.copy(bitmap.getConfig(), true); // Copy of the original, because we will potentially make changes to this
            maskedBitmap = originalBitmap.copy(originalBitmap.getConfig(), true);
            originalCanvas = new Canvas(originalBitmap);
            maskedCanvas = new Canvas(maskedBitmap);
        } else {
            originalBitmap = null;
            originalCanvas = null;
            maskedBitmap = null;
            maskedCanvas = null;
        }

        int undoSize = undoStack.size();
        int redoSize = redoStack.size();

        undoStack.clear();
        redoStack.clear();

        invalidate();

        if (listener != null) {
            if (undoSize != undoStack.size()) {
                listener.onUndoStackChanged(undoSize, undoStack.size());
            }
            if (redoSize != redoStack.size()) {
                listener.onRedoStackChanged(redoSize, redoStack.size());
            }
        }
    }

    public StackListener getListener() {
        return listener;
    }

    public void setListener(StackListener listener) {
        this.listener = listener;
    }

    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                int undoSize = undoStack.size();
                int redoSize = redoStack.size();

                // Max stack size. Remove oldest item before adding new
                if (undoStack.size() == MAX_STACK_SIZE) {
                    // The undo history does not go further back, so make the change permanent by updating the original canvas/bitmap
                    Pair<Float, Float> pair = undoStack.remove(0);
                    maskPoint(originalCanvas, pair.first, pair.second);
                }

                undoStack.push(new Pair<>(ev.getX(), ev.getY()));
                redoStack.clear();
                invalidate();

                if (listener != null) {
                    if (undoSize != undoStack.size()) {
                        listener.onUndoStackChanged(undoSize, undoStack.size());
                    }
                    if (redoSize != redoStack.size()) {
                        listener.onRedoStackChanged(redoSize, redoStack.size());
                    }
                }

                break;
            }

            case MotionEvent.ACTION_MOVE: {
                int undoSize = undoStack.size();
                int redoSize = redoStack.size();

                // Max stack size. Remove oldest item before adding new
                if (undoStack.size() == MAX_STACK_SIZE) {
                    // The undo history does not go further back, so make the change permanent by updating the original canvas/bitmap
                    Pair<Float, Float> pair = undoStack.remove(0);
                    maskPoint(originalCanvas, pair.first, pair.second);
                }

                maskPoint(maskedCanvas, ev.getX(), ev.getY());
                undoStack.push(new Pair<>(ev.getX(), ev.getY()));
                redoStack.clear();
                invalidate();

                if (listener != null) {
                    if (undoSize != undoStack.size()) {
                        listener.onUndoStackChanged(undoSize, undoStack.size());
                    }
                    if (redoSize != redoStack.size()) {
                        listener.onRedoStackChanged(redoSize, redoStack.size());
                    }
                }
                break;

            }

            case MotionEvent.ACTION_UP:
                invalidate();
                break;

        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (maskedBitmap != null) {
            canvas.drawBitmap(maskedBitmap, 0, 0, null);
        }
        super.onDraw(canvas);

    }

    public boolean undo() {
        if (!undoStack.empty()) {
            int undoSize = undoStack.size();
            int redoSize = redoStack.size();

            Pair<Float, Float> pair = undoStack.pop();
            // Redraw a single part of the original bitmap
            //unmaskPoint(maskedCanvas, pair.first, pair.second);

            // Redraw the original bitmap, along with all the points in the undo stack
            remaskCanvas(maskedCanvas);

            redoStack.push(pair); // Do not need to check for > 50 here, since redoStack can only contain what was in undoStack
            invalidate();

            if (listener != null) {
                if (undoSize != undoStack.size()) {
                    listener.onUndoStackChanged(undoSize, undoStack.size());
                }
                if (redoSize != redoStack.size()) {
                    listener.onRedoStackChanged(redoSize, redoStack.size());
                }
            }

            return true;
        }

        return false;
    }

    public boolean redo() {
        if (!redoStack.empty()) {
            int undoSize = undoStack.size();
            int redoSize = redoStack.size();

            Pair<Float, Float> pair = redoStack.pop();
            maskPoint(maskedCanvas, pair.first, pair.second);
            undoStack.push(pair); // Do not need to check for > 50 here, since redoStack can only contain what was in undoStack
            invalidate();

            if (listener != null) {
                if (undoSize != undoStack.size()) {
                    listener.onUndoStackChanged(undoSize, undoStack.size());
                }
                if (redoSize != redoStack.size()) {
                    listener.onRedoStackChanged(redoSize, redoStack.size());
                }
            }

            return true;
        }

        return false;
    }

    private void maskPoint(Canvas canvas, float x, float y) {
        if (canvas != null) {
            canvas.drawCircle(x, y, drawRadius, paint);
        }
    }

    private void unmaskPoint(Canvas canvas, float x, float y) {
        if (canvas != null) {
            Path path = new Path();
            path.addCircle(x, y, drawRadius, Path.Direction.CW);

            canvas.save();
            canvas.clipPath(path);
            canvas.drawBitmap(originalBitmap, 0, 0, new Paint());
            canvas.restore();
        }
    }

    private void remaskCanvas(Canvas canvas) {
        if (canvas != null) {
            canvas.drawBitmap(originalBitmap, 0, 0, new Paint());

            for (int i = 0; i < undoStack.size(); i++) {
                Pair<Float, Float> pair = undoStack.get(i);
                maskPoint(canvas, pair.first, pair.second);
            }
        }
    }

    public interface StackListener {
        void onUndoStackChanged(int previousSize, int newSize);

        void onRedoStackChanged(int previousSize, int newSize);
    }
}

您可能希望限制这些堆栈的大小,以便在用户拖动屏幕时不会溢出。你可以玩这个数字,但50对我来说似乎是一个好的开始。

修改

作为旁注,一次重做/撤消多个条目可能会很好。因为onTouchEvent会触发非常精细的动作。按下撤消/重做时用户不会注意到的移动。

编辑2

我已经添加到上面的实现中,以便处理撤消。我发现只在特定点重绘的策略不足,因为重叠点不正确。 (A点和B点重叠,删除B导致A的子部分被清除)。

因此我在撤销操作上重新屏蔽整个位图,这意味着撤消需要一个中间位图。如果没有中间位图,撤消操作将导致堆栈中不再存在的点(最多50个)也被删除。由于我们不支持通过该点的undo,因此使用原始位图作为中间位图就足够了。

这两种方法都在代码中,因此您可以测试它们。

最后,我添加了一个Listener,允许Activity知道堆栈的状态。启用/禁用按钮。

MainActivity

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final UndoCanvas canvas = (UndoCanvas) findViewById(R.id.undoCanvas);
        final Button undoButton = (Button) findViewById(R.id.buttonUndo);
        final Button redoButton = (Button) findViewById(R.id.buttonRedo);
        undoButton.setEnabled(false);
        redoButton.setEnabled(false);

        canvas.setListener(new UndoCanvas.StackListener() {
            @Override
            public void onUndoStackChanged(int previousSize, int newSize) {
                undoButton.setEnabled(newSize > 0);
            }

            @Override
            public void onRedoStackChanged(int previousSize, int newSize) {
                redoButton.setEnabled(newSize > 0);
            }
        });

        undoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvas.undo();
            }
        });

        redoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canvas.redo();
            }
        });

        canvas.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.image));
    }
}

截图

撤消前

Screen before undo operation(s)

撤消后

Screen after undo operation(s)