ANDROID - 在 canvas 中撤消和重做

ANDROID - Undo and Redo in canvas

我正在位图上绘制一个圆圈(触摸)以擦除 circle.How 中该区域的叠加位图,我是否为此添加撤消和重做功能?

编辑:请参考 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;
    }

如评论中所述,您可以保留 Stacks 来跟踪 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 个)也被删除。由于我们不支持撤消通过该点,因此使用原始位图作为中间位图就足够了。

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

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

主要Activity

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));
    }
}

截图

撤销前

撤消后