在swift中绘制弧线时的额外线条

我在一个快速的应用程序中有这种代码,我得到一条额外的灰色线到达弧的起点。 弧本身按预期绘制,但似乎CGContextMoveToPoint在到达起点之前留下一些痕迹。

 override func drawRect(rect: CGRect) { var context:CGContextRef = UIGraphicsGetCurrentContext(); var centerX,centerY,startAngle,endAngle,radius:CGFloat startAngle = CGFloat(M_PI_4) endAngle = -startAngle radius = (rect.height/2) / sin(startAngle) centerX = rect.width/2 + (radius*cos(startAngle)) centerY = rect.height/2 CGContextMoveToPoint(context, rect.width/2, rect.height) CGContextAddArc(context,centerX,centerY,radius,startAngle,endAngle,0); CGContextSetLineWidth(context, 3.0) CGContextSetStrokeColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextStrokePath(context) } 

什么可能是错的?

这是CGContextAddArc一个function。 从文档:

如果当前路径已包含子路径,Quartz会添加一条将当前点连接到弧的起点的线。 如果当前路径为空,Quartz会创建一个新的新子路径,其起点设置为弧的起始点。

通过移动到某一点,您已经建立了路径的起点。 如果删除CGContextMoveToPoint() ,则无需多余线条即可绘制弧线。

或者,您可以移动到弧的起点:

 CGContextMoveToPoint(context, centerX + radius*cos(startAngle), centerY + radius*sin(startAngle)) 

更新

(编者注:我在@Michel发现问题后添加了这一点。这可能是我在评论中进行一些讨论后应该给出的答案。这里提供的可能是为了帮助其他人)。

您的整个圆弧看起来像字母c,但只有部分圆弧在视图中可见(给定上面的代码)。 额外的线条从视图底部的中间绘制到屏幕外的c曲线的下部开始。

如果您只想要视图中弧线的一部分,那么您的起始角度应为3 * M_PI_4然后您的centerX计算需要使用-而不是+

 override func drawRect(rect: CGRect) { var context:CGContextRef = UIGraphicsGetCurrentContext(); var centerX,centerY,startAngle,endAngle,radius:CGFloat startAngle = 3 * CGFloat(M_PI_4) endAngle = -startAngle radius = (rect.height/2) / sin(startAngle) centerX = rect.width/2 - (radius*cos(startAngle)) centerY = rect.height/2 CGContextMoveToPoint(context, rect.width/2, rect.height) CGContextAddArc(context,centerX,centerY,radius,startAngle,endAngle,0); CGContextSetLineWidth(context, 3.0) CGContextSetStrokeColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextStrokePath(context) } 

然后,您的起点将在视图中,并且不会出现额外的行。