如何关闭三角形路径?

How to close triangle path?

我画了这个形状:

这是我的代码:

/* build path */
let bottomBezierPath = UIBezierPath()
//first thing draw bottom line
bottomBezierPath.moveToPoint(CGPointMake(0, TRIANGLE_EDGE))
bottomBezierPath.addLineToPoint(CGPointMake(bottomShapeLayer.frame.size.width,TRIANGLE_EDGE))

//now draw triangle
bottomBezierPath.moveToPoint(CGPointMake(bottomShapeLayer.frame.size.width,TRIANGLE_EDGE))
bottomBezierPath.addLineToPoint(CGPointMake(bottomShapeLayer.frame.size.width,0))
bottomBezierPath.moveToPoint(CGPointMake(bottomShapeLayer.frame.size.width,0))
bottomBezierPath.addLineToPoint(CGPointMake(bottomShapeLayer.frame.size.width - TRIANGLE_EDGE ,TRIANGLE_EDGE))

bottomShapeLayer.path = bottomBezierPath.CGPath
bottomShapeLayer.fillColor = UIColor.redColor().CGColor
bottomShapeLayer.strokeColor = UIColor.redColor().CGColor

但是我需要用红色填充三角形,bottomShapeLayer.fillColor 应该可以,对吧?

您正在为三角形创建 2 条单独的线段。

每次使用 moveToPoint() 时,都会开始一个新的线段。 因此,当 CAShapeLayer 开始填充三角形时,它无法填充它,因为它是 'incomplete'.

解决这个问题 真的 简单,您只需通过删除 moveToPoint() 调用之一为您的三角形创建一条连续路径:

let bottomBezierPath = UIBezierPath()
//first thing draw bottom line
bottomBezierPath.moveToPoint(CGPointMake(0, TRIANGLE_EDGE))
bottomBezierPath.addLineToPoint(CGPointMake(bottomShapeLayer.frame.size.width,TRIANGLE_EDGE))

//now draw triangle
//bottomBezierPath.moveToPoint(CGPointMake(bottomShapeLayer.frame.size.width,TRIANGLE_EDGE)) // this line is redundant btw, as you're moving to the same point. I've left it in incase you want to start your triangle somewhere else.
bottomBezierPath.addLineToPoint(CGPointMake(bottomShapeLayer.frame.size.width,0))
bottomBezierPath.addLineToPoint(CGPointMake(bottomShapeLayer.frame.size.width - TRIANGLE_EDGE ,TRIANGLE_EDGE))

还值得注意的是,您在三角形的 开始 处的 moveToPoint() 调用也是多余的,因为它正在移动到同一点。

现在你有了一个完整的三角形,它应该被正确填充了。