为什么在 Android SurfaceView 上绘制新形状时绘制的形状会消失?

Why do drawn shapes disappear when new shapes are drawn on Android SurfaceView?

我在 SurfaceView 的 OnTouch 事件上画圆圈。这是代码

public class DrawableSurface extends SurfaceView {
    public DrawableSurface(Context context) {
        super(context);
        surfaceHolder = getHolder();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);

        /*Handler handler = new Handler();
        handler.postDelayed(new Bubbles(handler) ,1000);*/
    }

    private final SurfaceHolder surfaceHolder;
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);



    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_MOVE)
        {
            Canvas canvas = surfaceHolder.lockCanvas();

            canvas.drawCircle(event.getX(), event.getY(), 50, paint);
            surfaceHolder.unlockCanvasAndPost(canvas);
        }
        return true;
    }
}

每当绘制新形状时,一些已绘制的形状就会消失。不是全部,但其中一些消失了。有时他们会回来。我想不通。为什么会这样?

SurfaceView 表面是双缓冲或三缓冲的。当缓冲区翻转时,您会看到事物消失并重新出现。

您需要在每一帧更新绘图区域中的每个像素。您可以通过将 Rect 传递给 lockCanvas() 来限制更新的像素数。有关详细信息,请参阅 lockCanvas() documentation