How to draw round dot stroke pattern for a CAShapeLayer?
Asked Answered
R

3

8

I am trying to stroke the paths in CAShapeLayer using dash patterns. I have created many dash patterns using lineDashPattern property. But this property doesn't give any option for type of dash stroked. I want to be my dashes to be round dots like in image below:

enter image description here

I know it can be achieved because I have seen this in many apps. But I am not able to find any way to implement this in CAShapeLayer library. So I want to know how to get these round dot dash pattern?

Rafi answered 22/11, 2014 at 11:43 Comment(0)
T
8

All you have to do is to set kCALineCapRound for the lineCap property of your CAShapeLayer and then set your lineDashPattern to [0.0, x ], where for example x is 2 * the line width of your CAShapelayer if you want the margin between the dots to be as long as your dots diameter.

The 0.0 for the first painted segment in lineDashPattern is there cause kCALineCapRound draws a semicircle in front of and behind your painted segment and any painted segment bigger than zero would cause the dot to become a pill.enter image description here

Totality answered 8/4, 2015 at 19:12 Comment(2)
Even if i set x = 2 * linewitdh it gives me pillsTownsley
X has nothing to do with the form of the dot, it defines the margin between the dots (the unpainted segment). The Zero in the example is what the dot forms, if the painted segment is bigger than zero it gives you a pill.Totality
I
5

try //swift

layer.strokeColor = UIColor.whiteColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
layer.lineWidth = 4
layer.lineDashPattern = [0.01, layer.lineWidth * 2]
layer.lineCap = kCALineCapRound
Ignacioignacius answered 26/6, 2016 at 8:12 Comment(0)
H
1

Try the below snippet

shapeLayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2 * stroke.width()], nil];
shapeLayer.lineCap = kCALineCapRound;
Hiroshima answered 8/10, 2015 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.