How to draw round dot stroke pattern for a CAShapeLayer?

4.3k views Asked by At

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?

3

There are 3 answers

2
Nein Danke On

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

0
prabu raj On

Try the below snippet

shapeLayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2 * stroke.width()], nil];
shapeLayer.lineCap = kCALineCapRound;
0
Alex On

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