UI: Fix typecast exception when trying to get Bitmap off a Drawable

This commit is contained in:
Vishal
2017-01-31 02:23:29 +05:30
parent e1d2c0860e
commit 11e49bec8e
@@ -37,7 +37,7 @@ public class RoundedImageView extends ImageView {
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap b = drawableToBitmap(drawable);
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();
@@ -76,6 +76,34 @@ public class RoundedImageView extends ImageView {
return output;
}
/**
* Converts a {@link Drawable} to {@link Bitmap}
* A drawable can be drawn on a {@link Canvas} and a Canvas can be backed by a Bitmap.
* Hence the conversion
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}