如何从UIView中删除CAShapeLayer和CABasicAnimation?

Thi*_*den 4 cabasicanimation cashapelayer cgpath swift swift-playground

这是我的代码:

@objc func drawForm() {
    i = Int(arc4random_uniform(UInt32(formNames.count)))
    var drawPath = actualFormNamesFromFormClass[i]
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.black.cgColor
    shapeLayer.lineWidth = 6
    shapeLayer.frame = CGRect(x: -115, y: 280, width: 350, height: 350)

    var paths: [UIBezierPath] = drawPath()
    let shapeBounds = shapeLayer.bounds
    let mirror = CGAffineTransform(scaleX: 1,
                                   y: -1)
    let translate = CGAffineTransform(translationX: 0,
                                      y: shapeBounds.size.height)
    let concatenated = mirror.concatenating(translate)

    for path in paths {
        path.apply(concatenated)
    }

    guard let path = paths.first else {
        return
    }

    paths.dropFirst()
        .forEach {
            path.append($0)
    }

    shapeLayer.transform = CATransform3DMakeScale(0.6, 0.6, 0)
    shapeLayer.path = path.cgPath

    self.view.layer.addSublayer(shapeLayer)

    strokeEndAnimation.duration = 30.0
    strokeEndAnimation.fromValue = 0.0
    strokeEndAnimation.toValue = 1.0
    shapeLayer.add(strokeEndAnimation, forKey: nil)
}
Run Code Online (Sandbox Code Playgroud)

这段代码为shapeLayer路径的绘图设置了动画,但我无法在网上找到任何关于删除此图层并停止此基本动画或删除被绘制的cgPath的内容...任何帮助将不胜感激!

Rob*_*Rob 6

你说:

我在网上找不到关于删除这一层的任何内容......

是的removeFromSuperlayer().

shapeLayer.removeFromSuperlayer()
Run Code Online (Sandbox Code Playgroud)

你继续说:

...并停止这个基本动画......

它是removeAllAnimations:

shapeLayer.removeAllAnimations()
Run Code Online (Sandbox Code Playgroud)

请注意,这将立即将strokeEnd(或您动画的任何属性)更改回其先前的值.如果你想,你停了"冻结",你必须抓住presentation层(因为它们是中期的动画捕捉图层的属性),保存相应的属性,然后更新您在其是该层的属性停止动画:

if let strokeEnd = shapeLayer.presentation()?.strokeEnd {
    shapeLayer.removeAllAnimations()
    shapeLayer.strokeEnd = strokeEnd
}
Run Code Online (Sandbox Code Playgroud)

最后,你继续说:

......或删除cgPath那个被绘制的.

只需将其设置为nil:

shapeLayer.path = nil
Run Code Online (Sandbox Code Playgroud)

顺便说一句,当你浏览了该文档CAShapeLayerCABasicAnimation,不要忘记检查出的文档的超类,也就是和CALayerCAAnimation» CAPropertyAnimation分别.最重要的是,当四处寻找有关特定类的属性或方法的文档时,您通常需要深入研究超类以查找相关信息.

最后,核心动画编程指南是很好的介绍,虽然它的例子在Objective-C中,但所有概念都适用于Swift.