/**
* @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.
* Source : http://stackoverflow.com/questions/7392062/android-
* semitransparent-bitmap-background-is-black/14858913#14858913
*/
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;
}
Using adjustOpacity
, I make ImageView
's Bitmap
be semi-transparent.
Bitmap newBitmap = adjustOpacity(orignalBitmap, 10);
view.setImageBitmap(newBitmap);
view.setBackgroundColor(Color.WHITE);
However, Imageview
show more darkent before not white. How do I make a semi-transparent (white background) Imageview with Bitmap
?
// Convert transparentColor to be transparent in a Bitmap.
public static Bitmap makeTransparent(Bitmap bit, Color transparentColor) {
int width = bit.getWidth();
int height = bit.getHeight();
Bitmap myBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int [] allpixels = new int [ myBitmap.getHeight()*myBitmap.getWidth()];
bit.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(),myBitmap.getHeight());
myBitmap.setPixels(allpixels, 0, width, 0, 0, width, height);
for(int i =0; i<myBitmap.getHeight()*myBitmap.getWidth();i++){
if( allpixels[i] == transparentColor)
allpixels[i] = Color.alpha(Color.TRANSPARENT);
}
myBitmap.setPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
return myBitmap;
}
The above code will take a Bitmap, and return a Bitmap where every pixel which the color is transparentColor is transparent. This works in API as low as level 8, and I have not tested it in any lower.
I typically use something like Color.RED to make my transparent pixels, because I don't use a lot of RED in my assets, but if I do it's a custom red color.
Try this. Also note that setAlpha is in 0-255 range
//bmp is your Bitmap object
BitmapDrawable bd = new BitmapDrawable(bmp);
bd.setAlpha(50);
ImageView v = (ImageView) findViewById(R.id.image);
v.setImageDrawable(bd);
try this,
newBitmap.setImageResource(android.R.color.transparent);
@akaya's answer is the right way except that the constructor is deprecated. The new way since API 4 would be to use:
BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
drawable.setAlpha(100);