使用CGContextSetLineDash绘制虚线

7

我正在尝试使用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];

然而,如果我画得慢一些,那些虚线就不会出现(参见下图的顶部),但是如果我画得快一些,它们就会出现(参见下图的底部)。为什么会这样呢?

1
我看不出这与Xcode有何关联。 - user529758
1个回答

4
您设置了dashPhase = 0,因此每次开始新的线条时,图案都以一个30个单位的绘制段开始,后跟一个30个单位的未绘制段。如果线段很短,整条线将被涂上颜色。
因此,您可以使用单个路径,在其中仅附加线段,或者为每个新的子路径计算开始图案的dashPhase
CGContextSetLineDash的最后一个参数不应该是dashLengths[]的长度吗,即2?) 更新:正如我们在讨论中发现的那样,解决问题的方法确实是在用户绘制相同曲线的同时向最后一个贝塞尔路径添加线段:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    // ...
    // Compute nextPoint to draw ...
    UIBezierPath *lastPath = [self.paths lastObject]; 
    [lastPath addLineToPoint:self.nextPoint];
    // ...
}

1
我根据您的评论更改了一些位,但是当我慢慢绘制虚线时,它们仍然会全部合并在一起。 - James Anderson
很可能“绘制缓慢”意味着捕获的点在视觉上非常接近,导致了您所描述的问题。我认为合理的方法是将线段附加到路径中,如果需要,重新绘制以确保虚线被正确绘制。 - Henri Normak
每秒大约绘制30个像素 - 这是我的更新代码:http://pastie.org/5099406 - James Anderson
@d3v3l0p3r101:你仍然使用固定的dashPhase,这不能与单独的路径段一起使用,因为每个段都从一个新的模式开始。正如Henri和我所建议的那样,你应该使用一个单一的路径,然后添加线段。 - Martin R
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/18423/discussion-between-martin-r-and-d3v3l0p3r101 - Martin R
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接