1
votes
CGContextRef currentContext = UIGraphicsGetCurrentContext();

CGContextSetStrokeColorWithColor(currentContext, hh2DarkGray.CGColor);
CGFloat lengths[] = {0, 8};
CGContextSetLineCap(currentContext, kCGLineCapRound);
CGContextSetLineWidth(currentContext, 1);
CGContextSetLineDash(currentContext, 0.0f, lengths, 2);

CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, x1, y1);
CGContextAddLineToPoint(currentContext, x2, y2);

CGContextClosePath(currentContext);
CGContextDrawPath(currentContext, kCGPathStroke);

What am I doing wrong in the above code that makes it so the dots are not evenly spaced? It looks like this.

. .. .. .. .. .. .. .. .. .. . when I need it to look like this . . . . . . . . . . . . . . .

I am completely lost and all other posts I can find don't point out this kind of issue. Please help?

2
[0, 4] for a dash pattern doesn't look like what you want. The documentation for CGContextSetLineDash says: For example, passing an array with the values [2,3] sets a dash pattern that alternates between a 2-user-space-unit-long painted segment and a 3-user-space-unit-long unpainted segment. Passing the values [1,3,4,2] sets the pattern to a 1-unit painted segment, a 3-unit unpainted segment, a 4-unit painted segment, and a 2-unit unpainted segment. - Mike Pollard
Could you maybe suggest some values then? I have been trying several different ways and have also read the documentation before. [0, 4] does evenly space it, but I need there to be more space between the dots. Right now I have it at 0, 8 and that's what it does above. I copied the wrong values. I will change that in the post. - user2282932
Try something other than '0' for the the length of the painted segment? Try {4,4}... - Mike Pollard
Thanks for the suggestion. When I do that I get this ----- Just longer drawn segments, but small spaces between - user2282932

2 Answers

4
votes

The problem is that you're closing the path – this implicitly draws a line back to the first point. If your path consists of just a straight line between two points, you basically get two lines drawn directly on top of each other, which causes the additional dots to appear (those are the second line with an offset in the dash pattern).

Solution: Just remove the call to CGContextClosePath.

It would also be more logical to use {1, 8} instead of {0, 8} as the dash pattern, since you want one point to be drawn, but in practice, it doesn't seem to make a difference.

0
votes

Try adding 0.5 to your line's coordinates:

CGContextMoveToPoint(currentContext, x1 + 0.5, y1 + 0.5);
CGContextAddLineToPoint(currentContext, x2 + 0.5, y2 + 0.5);

You have to think in logical coordinates and not in pixel indices. When you want to draw pixel perfect lines, you have to pass the coordinates of some pixels' center. Otherwise you'll get rounding artifacts.