Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing canvas with Canvas.drawColor()

i'm attempting to change the background image of a custom View with some success. the image will change but the problem is that i still see traces of the old image. when i attempt to clear the canvas before drawing the new image, it doesn't appear to work. i create a bitmap to store the image. when changing the image, i call Canvas.drawColor() before drawing the new image but the old image persists. i've tried drawColor(0), drawColor(Color.BLACK), c.drawColor(0, PorterDuff.Mode.CLEAR), and none of the above works. as such, i had to post this for review from more experienced minds than mine.

the actual code is as follows:

private int bgnd;
private boolean switching;

public void setBgnd(int incoming){
    switching = true;
    switch (incoming){

    case R.drawable.image1:
        bgnd = incoming;
        this.invalidate();
        break;

    case R.drawable.image2:
        bgnd = incoming;
        this.invalidate();
        break;

    }
}



protected void onDraw(Canvas c){
    if(switching == true){
        Bitmap b = BitmapFactory.decodeResource(getResources(), bgnd);
        c.drawColor(0, PorterDuff.Mode.CLEAR);
        c.drawBitmap(b, 0, 0, null);
        switching = false;

    }else{
        Bitmap b = BitmapFactory.decodeResource(getResources(), bgnd);
        c.drawBitmap(b, 0, 0, null);
    }
}
like image 506
Prmths Avatar asked Jan 10 '11 19:01

Prmths


3 Answers

Just like you, I struggled how to clear a top layer/surfaceview in my multiple layer/surfaceview app. After 2 days searching and coding, I found out my own way and this is how I cleared a canvas before drawing, you can use it when having multiple layers/surfaceviews. The background layer will not be covered with black, that is the trick.

Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvas.drawPaint(paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
// start your own drawing
like image 146
longdooooo Avatar answered Nov 20 '22 12:11

longdooooo


You can use Canvas's method drawRGB.

like image 30
ojs Avatar answered Nov 20 '22 13:11

ojs


Do you not need to also call invalidate() from within your onDraw method, so that changes made in that onDraw are updated on the screen?

The invalidate() in your switch will invoke your onDraw after you call setBgnd, but there's nothing saying to redraw after you've made changes to the Canvas.

like image 2
C0deAttack Avatar answered Nov 20 '22 13:11

C0deAttack