Getting Android vector drawable as Path

val vectorDrawable = ResourcesCompat.getDrawable(resources, R.drawable.icon, null)  vectorDrawable?.setBounds(0, 0, 800, 800) vectorDrawable?.draw(canvas)

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:

<path     
android:fillColor="#FF000000"
android:pathData="M17.6,9.48l1.84,-3.18c0.16,-0.31 0.04,-0.69 -0.26,..."/>
path.moveTo(17.6f, 9.48f) path.lineTo(19.44f, 6.3f) path.cubicTo(19.6f, 5.99f, 19.48f, 5.61f, 19.18f, 5.45f)
  • M is translated to moveTo
  • l is translated to lineTo
  • c is translated to cubicTo
  • First argument: 17.6 + 1.84 = 19.44
  • Second argument 9.48 3.18 = 6.3

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

A Path can be created from a String containing path instructions. There are two main steps to convert a vector drawable into Path:

  1. Parse content of a vector XML drawable and extract pathData attribute from it
  2. Create new Path object from path data
import androidx.core.graphics.PathParser  PathParser.createPathFromPathData(pathData)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store