Getting Android vector drawable as Path
You ever wondered how to get a
Path from Android’s vector XML drawable to draw it on canvas? Here are some options.
Getting a vector drawable and drawing it on a
canvas with any size is easy:
This produces a vector drawable which is properly scaled and looks sharp in most cases. Although if you scale this image too much some artifacts may appear, scaled icon may become blurry. Look how sharp the text is and how pixelated the scaled shape is:
In case you want to have better scaling and implement advanced features with paint, gradients and shaders you might need to get a vector drawable as instance of
Understanding XML path data
Each vector XML file contains instructions how to draw it. Compare parts of XML and Kotlin representation of the same icon:
This XML drawable contains path instructions which can be mapped into a set of
Mis translated to
lis translated to
cis translated to
Uppercase is for absolute coordinates, lowercase is for coordinates relative to previous instruction. Thus,
lineTo(19.44f, 6.3f). Quick maths:
- First argument: 17.6 + 1.84 = 19.44
- Second argument 9.48 - 3.18 = 6.3
It’s possible to manually build a
Path object that matches instructions of an XML drawable. Although it’ll probably take a lot of your time. It’s also easy to make a typo.
Read more about XML path data in this awesome article.
Generating Path code from vector image using an online generator
codecrafted.net/svgtoandroid is online generator that converts an SVG file into Java code, similar to what was demonstrated in the previous section. Resulting code can be optimized and improved by converting it to Kotlin and checking that all variables have meaningful names. Always think twice before uploading any of your app code including SVG icons into 3rd party services.
Converting vector XML into Path programmatically
Path can be created from a
String containing path instructions. There are two main steps to convert a vector drawable into
- Parse content of a vector XML drawable and extract
pathDataattribute from it
- Create new
Pathobject from path data
This gist shows how you can implement a parser for a simple XML with one
path node. Getting a
Path from path data string is trivial:
Look how sharp this shape is after scaling a
A complete example will be provided later as a part of a bigger project.