使用CGContextSetLineDash绘制一条虚线 [英] Drawing a dashed line with CGContextSetLineDash

查看:466
本文介绍了使用CGContextSetLineDash绘制一条虚线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 CGContextSetLineDash 画一条虚线。

I'm trying to draw a dashed line with 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];

但是,如果我画得很慢,它们的虚线就不会出现(见下图顶部)但是如果我快速绘制,它们会出现(见下图底部)。

However, if I draw slowly, they dashed lines do not appear (see top of image below) but if I draw quickly, they do appear (see bottom of image below).

为什么会发生这种情况?

Why is this happening?

推荐答案

您已设置 dashPhase = 0。,因此每次开始换行时,模式都会以30个单位绘制的段开头,然后是30单位未上漆的部分。如果线段很短,则整个线都会被绘制。

You have set dashPhase = 0., therefore each time you start a new line, the pattern starts with a 30 unit painted segment, followed by a 30 unit unpainted segment. If the line segments are short, the entire line will be painted.

因此要么使用单个路径,要么只追加线段,要么计算每个新线子路径 dashPhase 在哪里开始模式。

So either you use a single path, where you only append line segments, or you compute for each new subpath the dashPhase where to start the pattern.

(不应该是 CGContextSetLineDash 是 dashLengths [] 的长度,即 2 ?)

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

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

UPDATE: As we figured out in the discussion, the solution to the problem was indeed to add line segments to the last bezier path as long as 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];
    // ...
}

这篇关于使用CGContextSetLineDash绘制一条虚线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆