BlackBox BlackBox - 4 months ago 25
Android Question

Draw a bitmap (from a drawable) on a Canvas with a colored background

I'm doing a chess app and when I draw the tiles of the board, they don't get colored in the (transparent) background. Basically what I'd want, it's similar to what would happen in an ImageView that shows an image (with a transparent background) with a colored background.

This is the code

private final Paint squareColor;
private Rect tileRect;
private Drawable pieceDrawable;

public Tile(final int col, final int row) {
this.col = col;
this.row = row;

this.squareColor = new Paint();
squareColor.setColor(isDark() ? Color.RED : Color.WHITE);


}

public void draw(final Canvas canvas) {
if(pieceDrawable != null) {

Bitmap image = ((BitmapDrawable) pieceDrawable).getBitmap();
ColorFilter filter = new LightingColorFilter(squareColor.getColor(), Color.TRANSPARENT);
squareColor.setColorFilter(filter);
canvas.drawBitmap(image, null, tileRect, squareColor);
} else {
canvas.drawRect(tileRect, squareColor);
}
}


And this is how the chessboard looks like (left image)

1
2

If I comment out these 2 lines before
drawBitmap call
, I get the board as the right image.

ColorFilter filter = new LightingColorFilter(squareColor.getColor(), Color.TRANSPARENT);
squareColor.setColorFilter(filter);


My pieces are normal images with a transparent background where the piece is not drawn in the square. How can I have the red color behind the piece? (just as it would happen to an ImageView with the same images with a background color or onto a colored View)

Answer

You're only drawing the background if pieceDrawable is null. Change your code to:

public void draw(final Canvas canvas) {
    canvas.drawRect(tileRect, squareColor); // Draws background no matter if place is empty.
    if(pieceDrawable != null) {
        Bitmap image = ((BitmapDrawable) pieceDrawable).getBitmap();
        ColorFilter filter = new LightingColorFilter(squareColor.getColor(), Color.TRANSPARENT);
        squareColor.setColorFilter(filter);
        canvas.drawBitmap(image, null, tileRect, squareColor);
    }
}