动画UIBezierPaths-不工作 - 斯威夫特

时间:2017-03-24 18:16:36

标签: ios swift xcode animation

我正在尝试创建一个动画一起的箭头。但是,有两个问题:

1.线条没有动画,整个箭头只出现在屏幕上

2.箭头用黑色填充,而不仅仅是轮廓(我的目标)

let shapeLayer = CAShapeLayer()
let bezierPath = UIBezierPath()

//set up lines
bezierPath.move(to: CGPoint(x: 50.5, y: 158.5))
bezierPath.addLine(to: CGPoint(x: 221.5, y: 158.5))
bezierPath.addLine(to: CGPoint(x: 171.5, y: 108.5))
bezierPath.addLine(to: CGPoint(x: 197.5, y: 82.5))
bezierPath.addLine(to: CGPoint(x: 292.5, y: 177.5))
bezierPath.addLine(to: CGPoint(x: 197.5, y: 272.5))
bezierPath.addLine(to: CGPoint(x: 171.5, y: 246.5))
bezierPath.addLine(to: CGPoint(x: 221.5, y: 196.5))
bezierPath.addLine(to: CGPoint(x: 50.5, y: 196.5))
bezierPath.addLine(to: CGPoint(x: 50.5, y: 158.5))
UIColor.black.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
shapeLayer.path = bezierPath.cgPath

// set up animation
let animation2 = CABasicAnimation(keyPath: "strokeEnd")

animation2.fromValue = 0.0
animation2.toValue = 1.0
animation2.duration = 2.5
shapeLayer.add(animation2, forKey: "drawLineAnimation")

eeView.layer.addSublayer(shapeLayer)

如果有人能帮助我解决那些令人惊奇的问题。任何帮助都会非常感激!!非常感谢提前。

干杯, 西奥

1 个答案:

答案 0 :(得分:4)

问题在于这个序列:

shapeLayer.add(animation2, forKey: "drawLineAnimation")
eeView.layer.addSublayer(shapeLayer)

您无法将动画添加到图层,然后将图层添加到界面。您只能将动画添加到界面中的图层中。

此外,您需要设置形状图层的fillColorstrokeColor

这是实际的代码。在一个地方,你会说这样的话:

    let shapeLayer = CAShapeLayer()
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.black.cgColor
    eeView.layer.addSublayer(shapeLayer)
    self.shape = shapeLayer // self.shape is a property

然后,在稍后时间,你会说:

    let shapeLayer = self.shape!
    let bezierPath = UIBezierPath()
    // ... rest of your code goes here: create path, add path to shape layer ...
    // ... create animation, add animation to shape layer

enter image description here