Reputation: 744
I'm trying to create semitransparent bitmaps, I used this code:
private Bitmap SemiTransparent(Bitmap bitmap, int opacity) {
// Create an array to hold the data of bitmap for which semi transparent bitmap is to be obtained
int[] data = new int[(int)(bitmap.getWidth()) + 1];
for (int y = 0; y < bitmap.getHeight(); ++y)
{
// Get a single line of data
bitmap.getPixels(data, 0, bitmap.getWidth(), 0, y,bitmap.getWidth(), 1);
// Reset the alpha values
for (int x = bitmap.getWidth(); x>0; --x)
{
data[x] = (data[x] & 0x00ffffff) | (opacity << 24);
}
//fill alphaBitmap data
bitmap.setPixels(data, 0, bitmap.getWidth(), 0, y, bitmap.getWidth(), 1);
}
return bitmap;
}
The only problem is the background (transparent) color is always black - how can I modify this to make the background Color completely transparent and the rest still semitransparent?
Upvotes: 1
Views: 1645
Reputation: 4081
Use this method to make a bitmap transparent:
/**
* @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.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;
}
See an explanation here: http://blog.uncommons.org/2011/01/12/adjusting-the-opacity-of-an-android-bitmap/
In the blog-post it checks if the bitmap is mutable or not - which can cause problems if the bitmap is mutable but doesn't have the config ARGB_8888 - so use my method instead.
Upvotes: 2