Monday, December 14, 2015

Android code snippet to create transparent bitmaps

To reduce the storage needed on a phone for images, I wanted to use a single image file and programmatically set the transparency based on some attribute, e.g. age. The Android BitmapDrawable class has a setAlpha method but it does not work as expected and the resultant icons displayed in views remain as opaque as the original because of how Android handles image resources to minimise resource usage. Eventually, I found a workaround by drawing the icon onto a canvas with the desired transparency, then creating a new icon from the canvas. The following code snippet shows how.

private static Bitmap makeTransparentBitmap(Bitmap bmp, int alpha) {
        Bitmap transBmp = Bitmap.createBitmap(bmp.getWidth(),
                bmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(transBmp);
        final Paint paint = new Paint();
        canvas.drawBitmap(bmp, 0, 0, paint);
        return transBmp;

By using this code snippet, I was able to change the transparency of an icon image as shown in the screenshot below.

No comments:

Related Posts with Thumbnails