Skip to main content
 首页 » 操作系统

xcode之使用 CGContextDrawPath 时,如何避免在形状之间绘制线条

2024年01月01日36qlqwjy

我正在尝试绘制一系列小圆圈,但是当我使用 CGContextDrawPath 时,它会填充我添加到路径中的圆圈之间的线。这是代码:

  var radius: CGFloat = 3 
  var bulletSpacing: CGFloat = 10 
  var numberOfBullets = 5 
 
  override func drawRect(rect: CGRect) { 
 
    let ctx = UIGraphicsGetCurrentContext() 
 
    for i in 1...numberOfBullets{ 
      CGContextAddArc(ctx, CGFloat(Float(i) * Float(bulletSpacing)), self.frame.size.height/2, radius, 0, CGFloat(2 * M_PI), 0) 
    } 
 
    CGContextSetLineCap(ctx, kCGLineCapButt) 
    CGContextDrawPath(ctx, kCGPathStroke) 

有没有办法避免在圆圈之间绘制路径?这就是它最终的样子:

请您参考如下方法:

来自 CGContextAddArc() 的文档(强调已添加):

Adds an arc of a circle to the current path, possibly preceded by a straight line segment … If the current path already contains a subpath, Quartz adds a line connecting the current point to the starting point of the arc. … The ending point of the arc becomes the new current point of the path.

所以,经过一段圆弧后,圆弧的终点成为路径的当前点。然后,当添加下一个弧时,添加一条从前一个弧的终点到新弧的起点的线。

一种解决方案是在添加新弧之前立即将当前点移动到新弧的起点。您可以使用:

CGContextMoveToPoint(ctx, CGFloat(Float(i) * Float(bulletSpacing)) + radius, self.frame.size.height/2) 

另一种解决方案是在添加每个圆弧后绘制并清除路径。将对 CGContextSetLineCap() 的调用移到循环之前,并将对 CGContextDrawPath() 的调用移到循环中。