swift – 如何从我的UIView中删除CAShapeLayer和CABasicAnimation?

这是我的代码:

@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)
}

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

解决方法

你说:

I can’t find anything online about removing this layer …

这是removeFromSuperlayer().

shapeLayer.removeFromSuperlayer()

你继续说:

… and stopping this basic animation …

这是removeAllAnimations

shapeLayer.removeAllAnimations()

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

if let strokeEnd = shapeLayer.presentation()?.strokeEnd {
    shapeLayer.removeAllAnimations()
    shapeLayer.strokeEnd = strokeEnd
}

最后,你继续说:

… or removing the cgPath that gets drawn.

只需将其设置为nil:

shapeLayer.path = nil

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

最后,Core Animation Programming Guide是很好的介绍,虽然它的例子在Objective-C中,但所有概念都适用于Swift.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...