We can draw simple lines and shapes by using path.lineTo, path.moveTo etc. But sometimes we have requirements to draw a line in pattern, for example: simple dashed, two lines where 1 is continuous and other one is dashed etc.
Getting started
First we’ll have to create a small path that we want to repeat in the final path
// These are some sample methods to generate a single block of path // which will be repeated in the final path that we'll draw on canvas
// This will draw a small line with width 10px and length 30px privatefunmakeDefaultLinePath(): Path { val p = Path() p.moveTo(-15f, 5f) p.lineTo(15f, 5f) p.lineTo(15f, -5f) p.lineTo(-15f, -5f) return p }
// This will draw two small lines with width 4px and length 30px // They'll have 4px space between them privatefunmakeDoubleLinePath(): Path { val p = Path() p.moveTo(-15f, 6f) p.lineTo(15f, 6f) p.lineTo(15f, 2f) p.lineTo(-15f, 2f) p.close() p.moveTo(-15f, -6f) p.lineTo(15f, -6f) p.lineTo(15f, -2f) p.lineTo(-15f, -2f) return p }
// This will draw two small lines // One with width 4px and length 15px // Other with width 4px and length 30px // They'll have 4px space between them privatefunmakeBrokenSolidLinePath(): Path { val p = Path() p.moveTo(-15f, 6f) p.lineTo(0f, 6f) p.lineTo(0f, 2f) p.lineTo(-15f, 2f) p.close() p.moveTo(-15f, -6f) p.lineTo(15f, -6f) p.lineTo(15f, -2f) p.lineTo(-15f, -2f) return p }
We’ve create our building blocks of the final path. Now we’ll be setting PathEffect to the paint that will draw these blocks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// First setup your paint object val paint = Paint() paint.style = Paint.Style.STROKE paint.strokeWidth = 10f paint.color = Color.YELLOW
// Declare your pathDashPathEffect var pathDashPathEffect: PathDashPathEffect? = null
// Define your pathDashPathEffect pathDashPathEffect = PathDashPathEffect(makeDoubleLanePath(), //Your building block 45f, //At how much distance the next block should be drawn from the current block's starting point 0f, //Phase value PathDashPathEffect.Style.MORPH) //EffectStyle
// Set your defined pathDashPathEffect to your paint object pathDashPathEffect?.let { effect -> paint.pathEffect = effect }
We have our paint object with pathEffect with us. Now we’ll be drawing a path that we actaully want to draw using this paint object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var lineX1 = 0f var lineX2 = 0f var lineY1 = 0f var lineY2 = 0f val path = Path()