关于iPhone:使用CGContext SetLineDash绘制虚线

Drawing a dashed line with CGContextSetLineDash

我正在尝试用CGContextSetLineDash绘制虚线。

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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];

但是,如果我缓慢绘制,则不会出现虚线(请参见下图的顶部),但是如果我快速绘制,它们会出现(请参见下图的底部)。

enter


您已经设置了dashPhase = 0.,因此,每次您开始新行时,图案均以30单位的涂漆线段开头,然后是30单位的未涂漆线段。如果线段短,则将绘制整个线。

因此,您可以使用仅添加线段的单个路径,也可以为每个新的子路径计算dashPhase样式的起始位置。

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

更新:正如我们在讨论中所指出的那样,该问题的解决方案的确是只要用户绘制相同的曲线,就将线段添加到最后的贝塞尔曲线路径:

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