Question

I am trying to "erase" from a canvas. Just as a VERY simple test of clearing a canvas, I have implemented the following:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.argb(140, 0, 0, 0));
    canvas.drawColor(0, Mode.CLEAR);
}

Color.argb(140, 0, 0, 0) sets the view this view is drawn over to be dimmed. drawColor(0, Mode.CLEAR) makes the screen completely black, rather than removing the dimming applied earlier. The idea was taken from here

Was it helpful?

Solution

Use the following.

 canvas.drawColor(Color.TRANSPARENT,Mode.CLEAR);

OTHER TIPS

The solution was to create a secondary canvas and bitmap to draw on. My Custom View's onSizeChanged() method looked like

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    bitmap.eraseColor(Color.TRANSPARENT);
    temp = new Canvas(bitmap);
}

and the onDrawMethod looks like

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    temp.drawColor(Color.argb(80, 0, 0, 0));
    temp.drawCircle(centerPosX, centerPosY, 200, transparentPaint);
    canvas.drawBitmap(bitmap, 0, 0, null);
}

where transparentPaint is declared in the onstructor as

transparentPaint = new Paint();
transparentPaint.setColor(getResources().getColor(android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
transparentPaint.setAntiAlias(true);

You need to set the whole view to transparent, otherwise, the transparent color will be black.

At the constructor of the view that you are overwriting set the alpha to zero.

setAlpha(0); // this is the secret.

Then, at you onDraw() method, you can clear the view:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // ...
    canvas.drawColor(Color.TRANSPARENT,Mode.CLEAR);
    // do you painting here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top