Question

I have a PNG image (R.drawable.circle) that has a transparent background. I need to draw it in the canvas that is why I convert it into Bitmap. But I want the transparent background to be Color.WHITE. How do I do that? Is it possible?

private void drawer(Canvas canvas) {
      Bitmap animal = BitmapFactory.decodeResource(getResources(),R.drawable.circle);
      canvas.drawBitmap(Bitmap.createScaledBitmap(animal,100,100, false), 0, 0, null);
}
Was it helpful?

Solution

Try this way

private void drawer(Canvas canvas) {

        Bitmap bitmapOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.circle);
        Bitmap bitmapNew = Bitmap.createBitmap(bitmapOriginal.getWidth(), bitmapOriginal.getHeight(), Config.ARGB_8888);
        bitmapNew.eraseColor(Color.WHITE); // color that You want to set

        canvas.drawBitmap(bitmapNew, 0, 0, null);
        canvas.drawBitmap(bitmapOriginal, 0, 0, null);

    }

OTHER TIPS

Fill the canvas with your desired background color before drawing the bitmap, e.g.

canvas.drawColor(Color.WHITE);

As an aside, you shouldn't need to write low-level drawing code like that just to render a bitmap resouce on a background color. You can simply use an ImageView with src and background.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top