简体   繁体   中英

How to clear the Canvas (after drawing increasing circles) in a TextureView

I am trying to draw increasing circles in a TextureView. The centre of all circles is the same. I then try to increase the drawn Circle until a specific limit is reached. Then I want to clear the canvas and start over again. However using my code (see below), the canvas seems to never be cleared. Actually it flashes white shortly when it should be cleared, but then when the first circle in the next cycle is drawn (after attempting to clear canvas), all previous circles reappear and the whole animation seems to go crazy. After letting it run for several seconds I am left with dozens of circles (some overlapping) instead of only approximately 4 per cycle. Furthermore they do not have the radius I gave them (basically my code ends up drawing numerous circles of random sizes). Spent several days trying different things, but nothing seems to help.

Here's my code:

paint.setColor(Color.argb(opac, 177, 177, 177));
            stroke = 5;
            paint.setStrokeWidth(stroke);
            radius = 10;
            Canvas canvas = new Canvas();
            Boolean clear = false;
        //Added these two lines following advice from a previous answer:
        Paint clearPaint = new Paint();
        clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

        while (mRunning && !Thread.interrupted()) {

            canvas = mSurface.lockCanvas(null);
            try {   
                if(clear){
                    canvas.drawPaint(clearPaint); //This line should clear the canvas.
                    clear = false;
                }else{                      
                    canvas.drawCircle(circleX, circleY, radius, paint);
                }
            } finally {
                mSurface.unlockCanvasAndPost(canvas);
            }
            if(radius+15 <= circleY-stroke/2){
                radius+=15;
            }else{
                radius = 10;
                clear = true;
            }  
            try {
                Thread.sleep(360);
            } catch (InterruptedException e) {
                // Interrupted
            }

Would really appreciate it if someone could help me out here. I wasn't able to proceed with my project for several weeks now due to this problem.

Create a new Paint Instance for just clearing the canvas

Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

In your if() block for clearing the canvas, paint it with the above instance of Paint

if(clear){
    canvas.drawPaint(clearPaint);
    clear = false;
}

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