Dotted line drawing with CGContextSetLineDash

I am trying to draw a dashed line with CGContextSetLineDash .

Here is my code:

 float dashPhase = 0.0; float dashLengths[] = {30, 30}; CGContextSetLineDash(context, dashPhase, dashLengths, 20.0); self.previousPoint2 = self.previousPoint1; self.previousPoint1 = previous; self.currentPoint = current; self.mid1 = [self pointBetween:self.previousPoint1 andPoint:self.previousPoint2]; self.mid2 = [self pointBetween:self.currentPoint andPoint:self.previousPoint1]; UIBezierPath* newPath = [UIBezierPath bezierPath]; [newPath moveToPoint:self.mid1]; [newPath addLineToPoint:self.mid2]; [newPath setLineWidth:self.brushSize]; 

However, if I draw slowly, they dashed lines do not appear (see the upper part of the image below), but if I draw quickly, they appear (see the lower part of the image below).

enter image description here

Why is this happening?

+5
source share
1 answer

You set dashPhase = 0. so every time you start a new line, the template starts with a segment with a schedule of 30 units, followed by a 30-segment unpainted segment. If the line segments are short, the entire line will be colored.

Thus, either you use one path where you add only line segments, or calculate for each new dashPhase subdirectory where to start the template.

(Should the last parameter CGContextSetLineDash be the length of dashLengths[] , i.e. 2 ?)

UPDATE:. As we found out in the discussion, the solution to the problem really was to add line segments to the last bezier path while the user draws the same curve:

 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { // ... // Compute nextPoint to draw ... UIBezierPath *lastPath = [self.paths lastObject]; [lastPath addLineToPoint:self.nextPoint]; // ... } 
+4
source

Source: https://habr.com/ru/post/974703/


All Articles