Skip to content

Instantly share code, notes, and snippets.

@smac89
Created June 27, 2016 01:01
Show Gist options
  • Save smac89/b3cb4682dc6a59320376093aaaa27543 to your computer and use it in GitHub Desktop.
Save smac89/b3cb4682dc6a59320376093aaaa27543 to your computer and use it in GitHub Desktop.
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);
}
}
@smac89
Copy link
Author

smac89 commented Jun 27, 2016

Taken from this SO answer and modified to return BitmapDrawables instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment