Using vector drawables is often much better than bitmap images for two reasons: they scale without losing definition and you need only one asset file which fits all screen densities.
Sometimes I find it useful to create vector drawables by hand in Android Studio using SVG paths.
If you are not yet familiar with it, let me show you an example.
I’m going to create a rectangle consisting of two adjacent triangles varying in color like below:
android:height properties define the drawable intrinsic size, so it matters mostly when you later use the drawable with
wrap_content width and height like this:
android:viewportHeight properties are more important for us as they define the canvas size for drawing our paths.
Let’s fill a half of our squared canvas with the first triangle by drawing a path though its vertices: A, B and C.
Please note the coordinates — the top-left corner of the canvas is (0,0) and the bottom-right corner is (100,100) and that’s because we set the
You can draw a path by adding a
path inside the
We need the following SVG commands here:
Drawing the triangle consists of:
We could also use the relative lineto (
l) command instead and provide the vectors connecting the points like this:
It’s also worth noting that if you use the same command multiple times in a row, the command letter can be eliminated on subsequent commands. So the final command looks like this:
M 0,0 L 100,0 0,100 z
Let’s put this in the drawable file:
We can see the triangle in the preview panel:
As we already know how to draw a path, it’s very simple to create another triangle. Its vertices are:
so the path command is:
M 100,0 L 0,100 100,100 z
The resulting XML now looks like this:
Hint: you can name the paths so it’s easier to find them later if your drawable gets more complicated.
Now we can use the drawable. As you can see, it can be easily scaled by using the
This article is crossposted with author's personal blog.