Supporting VectorDrawable on pre-lollipop devices without generating png images.


Recently the android support library 23.2 was released, and one of the best thing about this release is that Vector images are now backward compatible up to API level 7.

So what does this mean to us as a developer?

1. No generation of png images at build time: Android Studio 1.4 handled backward compatibility by generating png images at build time. This is no longer required, so we must expect a reduction in build time.

2. Smaller size of apk : There is no need to generate different size images for mdpi, hdpi, xhdpi, etc. One vector file is enough to support multiple screen size devices. This will reduce the size of the apk.

In this post, we'll see how we can use vector images that support pre-lollipop devices.

Using VectorDrawables in your project

The first step we need to do is to prevent android studio from generating png files for our vector images at build time. We do that by adding the following code to the defaultConfig section of the app level gradle file

vectorDrawables.useSupportLibrary = true

It is recommended to use gradle 2.0+ for this.

Now to use a vector drawable we just need to use the app:srcCompat attribute as follows:

      app:srcCompat="@drawable/ic_add" />

We can also set the image at runtime as follows:

imageView.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_add));
Converting Vector Images to Bitmaps

There may be certain cases where you'll need to convert a vector image into a bitmap, for example, while creating a notification you'll need a bitmap for setting the LargeIcon of the notification. For this we can create the following function in our file as follows,

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawable) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);

        drawable = (DrawableCompat.wrap(drawable)).mutate();

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());

    return bitmap;

Hope you find this post useful. If you have any queries, feel free to connect with me at