所以我想为我正在为android工作的绘图应用程序实现一个撤销按钮。我目前的想法是将当前绘制路径放入MotionEvent.ACTION_UP上的路径列表中。在onDraw()中,只需绘制路径列表中的所有内容。当用户按下undo时,从路径列表中删除最后绘制的路径并调用invalidate(),强制调用onDraw(),这将绘制路径列表中的所有内容。由于我们从列表中删除了上一个路径,因此不应绘制该路径,因此应该“撤消”。
我遇到的问题是这条道路似乎永远不会被撤消。看起来我头脑中的逻辑是正确的,但这种实现方式无法正常工作。任何帮助将不胜感激。
这是我的代码:
DrawingView.java:
实例变量(以阐明以下方法):
private Context context;
private Path drawPath;
private Paint drawPaint;
private Paint canvasPaint;
private Canvas drawCanvas;
private Bitmap canvasBitmap;
private int previousPaintColor;
private int paintColor;
private float brushSize;
private float eraserSize;
private float lastBrushSize;
private boolean isErasing = false;
private List<Path> moveList = null;
private List<Path> undoList = null;
private List<Path> currentMoveList = null;
从构造函数调用:
private void setupDrawing() {
drawPath = new Path();
drawPaint = new Paint();
brushSize = getResources().getInteger(R.integer.default_brush_size);
lastBrushSize = brushSize;
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(brushSize);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
的onDraw:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
for (Path path : currentMoveList) {
canvas.drawPath(path, drawPaint);
}
for (Path path : moveList) {
canvas.drawPath(path, drawPaint);
}
}
的onTouchEvent:
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
currentMoveList.add(drawPath);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
moveList.add(drawPath);
drawPath = new Path();
currentMoveList.clear();
break;
default:
return false;
}
invalidate();
return true;
}
undo():
public void undo() {
if (moveList.size() > 0) {
undoList.add(moveList.remove(moveList.size() - 1));
invalidate();
}
}
此致
凯尔。
答案 0 :(得分:1)
经过一些试验和错误,以下是修复:
删除这行代码:
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
来自onDraw()方法,一切都很完美:)
答案 1 :(得分:0)
**撤消onDraw覆盖方法((TESTED))**
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
for (Path path : currentMoveList) {
canvas.drawPath(path, drawPaint);
}
for (Path path : moveList) {
canvas.drawPath(path, drawPaint);
}
super.onDraw(canvas);
}