smac89
6/27/2016 - 1:01 AM

Converts drawable image to BitmapDrawable

Converts drawable image to BitmapDrawable

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Canvas;

public static final class BitmapDrawableFromDrawable {
    public static BitmapDrawable drawableToBitmapDrawable (Context ctx, Drawable drawable) {
        Bitmap bitmap;

        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            if(bitmapDrawable.getBitmap() != null) {
                return bitmapDrawable;
            }
        }

        final int width = drawable.getMinimumWidth();
        final int height = drawable.getMinimumHeight();

        if(width <= 0 || height <= 0) {
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
        } else {
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return new BitmapDrawable(ctx.getResources(), bitmap);
    }
}