Vector Drawables for Fun and Profit

Tim Mutton
3 min readApr 1, 2016
Unlike Vector from Despicable Me, these vectors are not evil

One of the key new features of Lollipop was the ability to define drawables using vector graphics. These new vector drawables scale much better than their bitmap equivalents, with the added benefit of typically having a smaller file size (especially when you consider that you normally have to have at least 5 copies of each bitmap to support multiple screen densities).

Despite their obvious benefits vector drawables haven’t been a viable option until recently as they only work on devices running Lollipop or newer (which only represents 35.3% of Android devices as of February 2016). With the recent release of AppCompat 23.2.0, vector drawables are now supported on devices as old as API 7, which means we can finally start using this powerful new feature.

What Are Vector Drawables?

Vector drawables are a new type of drawable that is comprised of paths (as opposed to pixels) which are defined by a start and end point as well as any other points, curves or angles along the way. Vector drawables are based on a subset of the SVG format, which means that the path data of an SVG will work as a vector drawable path. As an example, the SVG image

would become the vector drawable

In this example the vector drawable is 2 KB in size whereas the bitmap equivalent would be 45 KB. The file size reduction of vector drawables is most apparent on simple shapes such as icons, however on sufficiently complex graphics such as photographs you may find that you actually increase the file size by converting it to vectors.

How Do I Use Them?

Whilst you can create a vector drawable by hand, the easiest way to include a vector drawable in your project is to import an SVG image that you’ve created in a vector graphics editor such as Inkscape, Adobe Illustrator or CorelDRAW. Android Studio’s vector asset tool makes the process of importing an SVG pretty straightforward, as shown below.

To use the vector drawable in your application, all you need to do is add AppCompat into your application’s dependencies and tell Gradle to use the support library for vector drawables (default behaviour is to rasterise vectors to bitmaps).

Once you’ve done this you can use the vector drawable in your ImageView (or subclasses such as ImageButton or FloatingActionButton) in the same way that you would normally use a bitmap drawable, with the only difference being that you have to use a new app:srcCompat key.

Wrapping Up

As with all things related to programming vector drawables are not a golden hammer, however when used correctly vector drawables can reduce the file size of your application and ensure that your images will scale well across all resolutions, orientations and form factors. Now that they are supported all the way back to API 7, there really isn’t any reason not to use them. So get cracking!

--

--