【问题标题】:Drawing a dashed line with CGContextSetLineDash使用 CGContextSetLineDash 绘制虚线
【发布时间】:2012-10-22 17:43:47
【问题描述】:

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

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

为什么会这样?

【问题讨论】:

  • 我看不出这与 Xcode 有什么关系。

标签: iphone objective-c ios cgcontext


【解决方案1】:

您已设置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];
    // ...
}

【讨论】:

  • 我根据您的 cmets 更改了一些位,但是,当我慢慢绘制虚线时,所有虚线都合并在一起
  • @d3v3l0p3r101:“慢慢地画”到底是什么意思?你能显示更新后的代码吗?
  • 最有可能“绘制缓慢”意味着捕捉到的点在视觉上彼此靠近导致您描述的问题。我认为合理的方法是将段附加到路径中,如果需要重新绘制以前的部分以确保正确绘制破折号。
  • 每秒画出 30 个像素左右 - 这是我更新的代码:pastie.org/5099406
  • @HenriNormak 我该怎么做呢?你能发布一个小例子作为答案吗? :-)
猜你喜欢
  • 1970-01-01
  • 2012-09-23
  • 2015-02-22
  • 2022-11-08
  • 2014-11-19
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
  • 2017-07-19
相关资源
最近更新 更多