我的CAShapeLayer未显示。我试图通过循环遍历CGPoints数组来创建一个形状。我需要使用数组或字典,以便稍后添加不同的CGPoints集来创建更复杂的形状。
var shapeLayer = CAShapeLayer()
var color = UIColor.redColor()
var openPath = UIBezierPath()
var closedPath = UIBezierPath()
let points = [CGPoint(x: 30, y: 30), CGPoint(x: 90, y: 30), CGPoint(x: 90, y: 90), CGPoint(x: 90, y: 30), CGPoint(x: 30, y: 30)]
var firstTime = false
override func viewDidLoad()
{
super.viewDidLoad()
setOpenPath()
}
func setOpenPath()
{
for number in points
{
if number != points.first
{
openPath.addLineToPoint(number)
}
if number == points.first
{
if firstTime == false
{
openPath.moveToPoint(number)
}
if firstTime == true
{
openPath.addLineToPoint(number)
setClosePath()
}
firstTime = true
}
}
}
func setClosePath()
{
firstTime = false
closedPath.CGPath = CGPathCreateMutableCopy(openPath.CGPath)
closedPath.closePath()
setShapeLayer()
}
func setShapeLayer()
{
shapeLayer.path = closedPath.CGPath
shapeLayer.fillColor = UIColor.greenColor().CGColor
shapeLayer.fillRule = kCAFillRuleNonZero
self.view.layer.addSublayer(shapeLayer)
}
如果我用下面的代码替换setOpenPath()中的代码,脚本工作正常。
openPath.moveToPoint(CGPoint(x: 30, y: 30))
openPath.addLineToPoint(CGPoint(x: 90, y: 30))
openPath.addLineToPoint(CGPoint(x: 90, y: 90))
openPath.addLineToPoint(CGPoint(x: 30, y: 90))
openPath.addLineToPoint(CGPoint(x: 30, y: 30))
setClosePath()
答案 0 :(得分:1)
你的点在points
数组中搞砸了。与下面的代码相比,索引3处的元素是错误的。它不会产生封闭的路径。
let points = [CGPoint(x: 30, y: 30), CGPoint(x: 90, y: 30), CGPoint(x: 90, y: 90), CGPoint(x: 30, y: 90), CGPoint(x: 30, y: 30)]
还可以使用其他条件并像这样简化循环
func setOpenPath()
{
firstTime = true
for number in points
{
if number != points.first
{
openPath.addLineToPoint(number)
}
else
{
if firstTime
{
openPath.moveToPoint(number)
}
else
{
openPath.addLineToPoint(number)
setClosePath()
}
firstTime = false
}
}
}