gpt4 book ai didi

java - Android绘图应用程序中的撤消按钮

转载 作者:太空狗 更新时间:2023-10-29 14:17:49 27 4
gpt4 key购买 nike

所以我想为我正在为 android 开发的绘图应用程序实现一个撤消按钮。我目前的想法是将当前绘制路径放入 MotionEvent.ACTION_UP 上的路径列表中。在 onDraw() 中,简单地绘制路径列表中的所有内容。当用户按下撤消键时,您将从路径列表中删除最后绘制的路径并调用 invalidate(),强制调用 onDraw(),这将绘制路径列表中的所有内容。由于我们从列表中删除了先前的路径,因此不应绘制该路径,因此应“撤消”。

我遇到的问题是路径似乎永远不会真正被撤消。看来我脑子里的逻辑是正确的,但是这个实现不能正常工作。任何帮助将不胜感激。

这是我的代码:

绘图 View .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);
}

绘制:

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

撤销() :

public void undo() {
if (moveList.size() > 0) {
undoList.add(moveList.remove(moveList.size() - 1));
invalidate();
}
}

问候,

凯尔。

最佳答案

经过反复试验,这里是修复:

删除这行代码:

canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);

来自 onDraw() 方法,一切正常:)

关于java - Android绘图应用程序中的撤消按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075560/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com