简体   繁体   中英

Android SurfaceView/Canvas flickering after trying to clear it

So I am trying to clear the Canvas using canvas.drawColor(Color.BLACK) but if I just call this once, the display flickers and displays the old drawing which should have been covered up by the drawColor.

Here is the important bits of my code -

// This method is called by a Thread                
public void update() {
    Canvas canvas = holder.lockCanvas(null);
    if (canvas != null) {
        onDraw(canvas);
    }
    holder.unlockCanvasAndPost(canvas);
}

@Override
protected void onDraw(Canvas canvas) {

    if (toClear) {
        canvas.drawColor(Color.BLACK);

        //if this is not set to change back to false, it does not flicker
        toClear = false;
    }

    //Draw some objects that are moving around
}

public void clearScreen() {     
    // This method is called when the user pressed a button
    toClear = true;
}

After Googling around a litte, I heard about double buffering but came to the understanding that lockCanvas() and unlockCanvasAndPost() should handle this for me. What is going wrong here?

I had the same problem in the past, or at least it sounds similar to your description. The way I solved it was to avoid calling the onDraw method, since the framework also calls this method BETWEEN your calls to it in the run method of your thread.

In short, rename your onDraw method to something like Render(), and then call Render from your run loop. If you still want to clear the screen, then simply do it within your run loop (before you call Render), this solved my "random sprites being drawn" issue.

Please let me know if this helps - it worked perfectly for me.

I wonder if this is to do with SurfaceView being double buffered and they alternate each frame. Hence you would have to clear the screen at least two frames.

Change toClear = true into toClear = 2 and set

if(toClear > 0) { 
   'drawColor'
   toClear--; 
}
  1. Have you read the docs on SurfaceHolder ? I'd make sure you're following all the recommended uses for calling from another thread.

  2. Are you sure your other objects are not simply being drawn after you've done your black fill? You mention drawing moving objects, and say it does not flicker if you don't reset your clear flag. Maybe it's being drawn twice? Have you placed a debug break point in that method to verify what's happening and when/how often it is called?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM