OGeek|极客世界-中国程序员成长平台

标题: ios - 如何关闭三角形路径? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:16
标题: ios - 如何关闭三角形路径?

我画了这个形状:

enter image description here

这是我的代码:

/* 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应该这样做,对吧?



Best Answer-推荐答案


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

每次使用 moveToPoint() 时,都会开始一个新的线段。因此,当 CAShapeLayer 来填充三角形,无法填充它,因为它“不完整”。

解决这个问题真的很简单,您只需通过删除 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() 也是多余的,因为它正在移动到同一点。

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

enter image description here

关于ios - 如何关闭三角形路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35343021/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4