liltof liltof - 1 year ago 1027
Android Question

Getting Bitmap from vector drawable

In my application, I have to set a large icon for a notification.
LargeIcon must be a Bitmap, and my drawables are vector images (the new feature in Android, see this link)
The problem is when I try to decode a resource that is a vector image, I get a null returned.

Here is the sample of code :

if (BitmapFactory.decodeResource(arg0.getResources(), R.drawable.vector_menu_objectifs) == null)
Log.d("ISNULL", "NULL");
Log.d("ISNULL", "NOT NULL");

In this sample, when I replace R.drawable.vector_menu_objectifs with a "normal" image, a png for exemple, the result is not null (I get the correct bitmap)
Is there something I'm missing?

Answer Source

You can use the following method:

private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
            vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    return bitmap;

which I sometimes combine with:

private static Bitmap getBitmap(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof VectorDrawable) {
        return getBitmap((VectorDrawable) drawable);
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download