用CGContextSetLineDash绘制一条虚线

我试图用CGContextSetLineDash画一条虚线。

这是我的代码:

 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]; 

但是,如果我画慢,他们的虚线不会出现(见下图),但如果我快速绘制,它们确实出现(见下图)。

在这里输入图像说明

为什么发生这种情况?

你已经设置了dashPhase = 0. ,因此每当你开始一个新的行时,模式以一个30单位绘制的段开始,接着是一个30单位的未上漆的段。 如果线段较短,整行将被绘制。

因此,无论是使用单个path,只添加线段,还是为每个新子path计算dashPhase启动模式的位置。

(不应该CGContextSetLineDash的最后一个参数是dashLengths[]的长度,即2 ?)

更新:正如我们在讨论中发现的那样,只要用户绘制相同的曲线,问题的解决scheme确实是将线段添加到最后一个贝塞尔path:

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