skippy skippy - 6 months ago 15
iOS Question

iOS CG dashed line path

Drawing dashed line path like this is very simply

enter image description here

CGFloat lengths[] = { 12.0, 4.0, 12.0, 4.0, 4.0, 4.0 };
CGContextSetLineDash(ctx, 0, lengths, 6);
//... path code: moveTo, lineTo, strokePath


Is possible to draw more complicated dashed line?
Example:

enter image description here

Rob Rob
Answer

You've created a path with six lengths. Create another with 8 to represent just the end points of those wider segments:

CGFloat lengths[]  = { 12.0,           4.0, 12.0,          4.0,  4.0, 4.0 };
CGFloat lengths2[] = {  3.0, 6.0, 3.0, 4.0, 3.0, 6.0, 3.0, 12.0 };

So, stroke the path twice, once with a narrow line width using CGContextSetLineDash of lengths and then again, a second time, with a thicker line width with CGContextSetLineDash of lengths2. For example, drawing this second one with a wider line width in red, it looks like:

enter image description here

If you draw both in black, it looks like:

enter image description here

Tweak the values as you see fit, but just make sure that the total of all of the lengths for both add up to the same value and so the stroked portions of lengths2 line up with the start and end of the segments in lengths.

Comments