清除功能在自定义SurfaceView Android中不起作用

我有一个自定义SurfaceView,它将根据Touch事件绘制表面。 当我在这个视图上画东西时,它工作正常。 但是当我试图擦除油漆时,没有任何东西被抹去。 请在下面找到示例代码片段:

public class MySurfaceView extends SurfaceView {
private static final String TAG = "FreeHandDrawing";
public static Canvas mCanvas;
SurfaceHolder holder;
private static Path path;
private Paint paint;
private ArrayList<Path> pathArrayList = new ArrayList<>();
private boolean freeHandMode;

public MySurfaceView(Context context, AttributeSet attrs) {
    super(context, attrs);
    freeHandMode = false;
    path = new Path();
    holder = getHolder();
    holder.setFormat(PixelFormat.TRANSPARENT);
    setDrawingCacheEnabled(true);

    this.setZOrderOnTop(true);

    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(0xFF22FF11);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeCap(Paint.Cap.ROUND);
    paint.setStrokeWidth(8);

}


@Override
public boolean onTouchEvent(MotionEvent event) {

    if(freeHandMode) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            Log.d("Action", "Placed");
            path.moveTo(event.getX(), event.getY());

        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {

            Log.d("Action", "Moved");
            path.lineTo(event.getX(), event.getY());
            pathArrayList.add(path);

        }

        mCanvas = holder.lockCanvas();
        if (mCanvas != null) {
            if (pathArrayList.size() > 0) {

                mCanvas.drawPath(pathArrayList.get(pathArrayList.size() - 1), paint);

            }
            holder.unlockCanvasAndPost(mCanvas);

        } else {
            Log.d(TAG, "Canvas is NULL");
        }
    }
    invalidate();
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.d(TAG, "On draw called");

}

public void eraseDrawing() {
    pathArrayList.clear();
    invalidate();
}

public void drawEnableDisable(boolean mode) {
    freeHandMode = mode;
  }
}                                                  

上面的代码有什么问题?


你应该在onDraw方法中保存你的绘图代码

@Override
protected void onDraw(Canvas canvas) {
    // In case you want to delete/erase when path array/list is cleared.
    if (pathArrayList.size() == 0) {
        canvas.drawColor(0, Mode.CLEAR);
    }
    // In case, you want to draw all paths also in onDraw
    for(Path path : pathArrayList) {
        canvas.drawPath(path, paint);
    }
}

清除路径数组(列表)然后调用invalidate()时,onDraw被触发。

注意:你应该在onTouchEvent()的末尾调用invalidate()来告诉系统更新屏幕。 调用invalidate()会让框架最终调用onDraw()。

也不应该使用lockCanvas获得的canvas ,因为它不会被硬件加速。 相反,您应该使用作为参数传递给onDraw()本身的画布。

你可以选择让系统变得有点聪明,因为不必每帧画出路径的拉列表,而是通过使用特殊标志来处理擦除/重绘等。 否则,只需渲染最近一次调用onTouchEvent()所生成的最新路径。

链接地址: http://www.djcxy.com/p/66775.html

上一篇: Erase functionality not working in Custom SurfaceView Android

下一篇: surfaceview disappears when i call setZOderOnTop(true)