I had to draw a dotted line today. Wow. It had to be round dots.
I found this snippet on StackOverflow.
CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat lengths[2]; lengths[0] = 0; lengths[1] = dotDiameter * 2; CGContextSetLineCap(context, kCGLineCapRound); CGContextSetLineWidth(context, dotDiameter); CGContextSetLineDash(context, 0.0f, lengths, 2);
I loved his comment to his code: “This should work correctly.”
The thing is, it didn’t quite. The dots didn’t look quite round, but sort of stretched. So I wanted to figure out why that is. (Answer, I never did, but thank you fudge factors and trial and error.) But I did set about visualizing these above parameters and have summarized it in a sketch:
So, perhaps that is of some help to you. Note, the image is displaying what you’d see if lengths were both dotDiameter.
In the end however, I just had to create some fudge factors to make it look right:
CGFloat dotDiameter = 6; CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat lengths[2]; lengths[0] = 0.0001; // Arguably FUDGE lengths[1] = dotDiameter * 2.5f; // FUDGE CGContextSetLineCap(context, kCGLineCapRound); CGContextSetLineWidth(context, dotDiameter * 1.2f); // FUDGE CGContextSetLineDash(context, 0.0f, lengths, 2);
Sometimes I’m a blacksmith programmer. Just keep pounding the metal until it has the right shape. This is one of those times. 🙂