我正在开发一个绘图应用,我想用重做/撤消选项实现橡皮擦功能。我已经浏览了CanvasView和FingerPaint个样本,但遗憾的是我无法实现橡皮擦。我使用了 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR) ))用于擦除但不起作用。
注意:在我的情况下橡皮擦正在工作,但重做/撤消不起作用,我希望两者都能正常工作。
我的代码:
//Here is the I am creating Paint object...
private Paint createPaint() {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(this.paintStyle);
paint.setStrokeWidth(this.paintStrokeWidth);
paint.setStrokeCap(this.lineCap);
paint.setStrokeJoin(Paint.Join.MITER); // fixed
if (this.mode == Mode.ERASER) {
// Eraser
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
paint.setARGB(0, 0, 0, 0);
// paint.setColor(this.baseColor);
// paint.setShadowLayer(this.blur, 0F, 0F, this.baseColor);
} else {
// Otherwise
paint.setColor(this.paintStrokeColor);
paint.setShadowLayer(this.blur, 0F, 0F, this.paintStrokeColor);
paint.setAlpha(this.opacity);
paint.setPathEffect(this.drawPathEffect);
}
return paint;
}
//This method is for managing Redo/Undo
private void updateHistory(Path path) {
if (this.historyPointer == this.pathLists.size()) {
this.pathLists.add(path);
this.paintLists.add(this.createPaint());
this.historyPointer++;
} else {
// On the way of Undo or Redo
this.pathLists.set(this.historyPointer, path);
this.paintLists.set(this.historyPointer, this.createPaint());
this.historyPointer++;
for (int i = this.historyPointer, size = this.paintLists.size(); i < size; i++) {
this.pathLists.remove(this.historyPointer);
this.paintLists.remove(this.historyPointer);
}
}
}
private void onActionDown(MotionEvent event) {
switch (this.mode) {
case DRAW :
case ERASER :
this.updateHistory(this.createPath(event));
this.isDown = true;
default :
break;
}
}
private void onActionMove(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (this.mode) {
case DRAW :
case ERASER :
Path path = this.getCurrentPath();
switch (this.drawer) {
case PEN :
path.lineTo(x, y);
break;
default :
break;
}
break;
default :
break;
}
}
private void onActionUp(MotionEvent event) {
if (isDown) {
this.startX = 0F;
this.startY = 0F;
this.isDown = false;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Before "drawPath"
canvas.drawColor(this.baseColor);
if (this.bitmap != null) {
canvas.drawBitmap(this.bitmap, 0F, 0F, emptyPaint);
}
for (int i = 0; i < this.historyPointer; i++) {
Path path = this.pathLists.get(i);
Paint paint = this.paintLists.get(i);
canvas.drawPath(path, paint);
}
this.canvas = canvas;
}
答案 0 :(得分:0)
/**
* This method draws canvas again for Undo.
*/
public boolean undo() {
if (this.historyPointer > 1) {
this.historyPointer--;
this.invalidate();
return true;
} else {
return false;
}
}
/**
* This method draws canvas again for Redo.
*/
public boolean redo() {
if (this.historyPointer < this.pathLists.size()) {
this.historyPointer++;
this.invalidate();
return true;
} else {
return false;
}
}