How to change a bitmap's opacity? How to change a bitmap's opacity? android android

How to change a bitmap's opacity?


As far as I know, opacity or other color filters can't be set on the Bitmap itself. You will need to set the alpha when you use the image:

If you're using ImageView, there is ImageView.setAlpha().

If you're using a Canvas, then you need to use Paint.setAlpha():

Paint paint = new Paint();paint.setAlpha(100);canvas.drawBitmap(bitmap, src, dst, paint);

Also, incorporating WarrenFaith's answer, if you will use the Bitmap where a drawable is required, you can use BitmapDrawable.setAlpha().


You could also try BitmapDrawable instead of Bitmap. If this is useful for you depends on the way you use the bitmap...

Edit

As a commenter asked how he can store the bitmap with alpha, here is some code:

// lets create a new empty bitmapBitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);// create a canvas where we can draw onCanvas canvas = new Canvas(newBitmap);// create a paint instance with alphaPaint alphaPaint = new Paint();alphaPaint.setAlpha(42);// now lets draw using alphaPaint instancecanvas.drawBitmap(originalBitmap, 0, 0, alphaPaint);// now lets store the bitmap to a file - the canvas has drawn on the newBitmap, so we can just store that one// please add stream handling with try/catch blocksFileOutputStream fos = new FileOutputStream(new File("/awesome/path/to/bitmap.png"));newBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);


public Bitmap makeTransparent(Bitmap src, int value) {      int width = src.getWidth();    int height = src.getHeight();       Bitmap transBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);       Canvas canvas = new Canvas(transBitmap);       canvas.drawARGB(0, 0, 0, 0);        // config paint        final Paint paint = new Paint();        paint.setAlpha(value);        canvas.drawBitmap(src, 0, 0, paint);            return transBitmap;}