Dan is the founder of Rectangular Software, an independent UK software company that provides development services and builds its own mobile and web applications. Dan has over a decade of experience in the software industry, building a wide variety of systems including casino, poker and spread-betting platforms, mobile applications, e-commerce websites, and network security software. His other programming interests include artificial intelligence, particularly evolutionary computation, and functional programming in Haskell. He has authored, or contributed to, a number of open source Java projects. Dan has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

Adjusting the Opacity of an Android Bitmap

  • submit to reddit

This took me a lot longer to figure out than it should have done. I’m documenting it here in case it’s useful for somebody else searching for a similar solution.

If you’re displaying the Bitmap in an ImageView, you can probably use the ImageView.setAlpha(int) method. However, if the ImageView is accesed via RemoteViews, as is the case when updating a widget, you won’t be able to invoke this method (if you try to call it via RemoteViews.setInt(int, String, int) you’ll get an exception telling you as much).

After much searching I was unable to find a widget-friendly mechanism for adjusting an ImageView‘s transparency, or any obvious way of manipulating a Bitmap‘s alpha channel.

Eventually I stumbled upon Kevin Dion’s excellent answer to a different but related question on StackOverflow. From this I was able to figure out that I needed to use the DST_IN Porter-Duff mode to modify the alpha channel.

* @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.
private Bitmap adjustOpacity(Bitmap bitmap, int opacity)
Bitmap mutableBitmap = bitmap.isMutable()
? bitmap
: bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
int colour = (opacity & 0xFF) << 24;
canvas.drawColor(colour, PorterDuff.Mode.DST_IN);
return mutableBitmap;

From http://blog.uncommons.org/2011/01/12/adjusting-the-opacity-of-an-android-bitmap/

Published at DZone with permission of its author, Dan Dyer.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)