Created
June 27, 2016 01:01
-
-
Save smac89/b3cb4682dc6a59320376093aaaa27543 to your computer and use it in GitHub Desktop.
Converts drawable image to BitmapDrawable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from this SO answer and modified to return
BitmapDrawable
s instead