Categories

Links

In our application we need to apply mask to some icons to make them semitransparent. The original images are in RGB format i.e. without alpha channel. To apply mask we need add alpha channel to original images. Before Android 2.0 we did this like:

Bitmap dest = src.copy(Bitmap.Config.ARGB_8888, true);

When we run our application on Android 2.1 device we noticed that the destination bitmap is created but without alpha channel. After applying mask, pixels that should be semitransparent become black.

The getPixel() method returns different value than was set by setPixel() method.

So, how to add alpha channel to RGB bitmap?

There are three ways:

First:

Use ARGB_4444 format:

Bitmap dest = src.copy(Bitmap.Config.ARGB_4444, true);

In this case the alpha channel will be added, but you will lose the quality of image

Second:

Create empty bitmap with dimensions of original image and ARGB_8888 format:

There is a better way to mask Bitmaps. I’ve talked about it in my blog : http://android.cyrilmottier.com/?p=230 (it’s in French but I’m sure you can read it using Google Translate or by simply reading the provided code). To sum up, the trick is to use the Xfermode on your Paint.

As you said, the first method is not perfect as you’re losing quality

The second method is very slow because you’re modifying bitmap in Java.

Hope it will help you 🙂

Nathan

API level 12 added a method setHasAlpha() which you can use instead of having to copy the image to get the alpha channel.

Nino Bozzi

GREAT SOLUTION!!!, the second… it avoids the setHasAlpha() when you aren’t on api 12.

Balazs Balazs

The idea is the same but here’s a more complete code, extracted nicely in a method:

/**
* @param bitmap The source bitmap.
* @param opacity a value between 0 (completely transparent) and 255 (completely
* opaque).
* @return The opacity-adjusted bitmap. If the source bitmap is mutable it will be
* adjusted and returned, otherwise a new bitmap is created.
*/