我无法让这个 CA 动画正常工作

I'm having trouble getting this CA animation to work

我正在尝试制作一个动画,其中红色脉冲在屏幕上闪烁,当点击屏幕时脉冲速度增加。现在我有两个问题。一,是动画不发生,二是动画必须加速,不重启动画。我希望动画从点击屏幕时的任何一点开始加速。

class ViewController: UIViewController {

var tapCount: Int = 0
var pulseSpeed: Double = 3
let pulseAnimLayer = CALayer()
let pulseAnim = CABasicAnimation(keyPath: "Opacity")

override func viewDidLoad() {
    super.viewDidLoad()

    counter.center = CGPoint(x: 185, y: 118)

    pulseAnim.fromValue = 0.5
    pulseAnim.toValue = 1.0
    pulseAnim.duration = 3.0
    pulseAnim.autoreverses = true
    pulseAnim.repeatCount = .greatestFiniteMagnitude
    pulseAnimLayer.add(pulseAnim, forKey: "Opacity")
}

func pulseAnimation(pulseSpeed: Double) {
    UIView.animate(withDuration: pulseSpeed, delay: 0,
        options: [UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse],
        animations: {
            self.red.alpha = 0.5
            self.red.alpha = 1.0
        }
    )
}

@IBOutlet weak var red: UIImageView!
@IBOutlet weak var counter: UILabel!

@IBAction func screenTapButton(_ sender: UIButton) {
    tapCount += 1
    counter.text = "\(tapCount)"
    pulseSpeed = Double(3) / Double(tapCount)
    pulseAnim.duration = pulseSpeed
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}
}  

第一次看的不够仔细。

您在这里混合了核心动画和 UIView 动画。两者存在于不同的层面。 Core Animation 将允许您在视图上为 属性 设置动画(比如说它的背景颜色)。

UIView 动画建立在 Core Animation 之上,通过构建底层 Core Animations 可以更轻松地自动动画视图更改。

当您创建一个 CABasicAnimation 时,您从 Core Animation 开始,但随后您有一个函数,pulseAnimation,它看起来正在使用 UIVIew 动画做一些事情。我认为您可以完全摆脱该功能。

当您添加 CABasicAnimation 时,您告诉它更改图层 "Opacity" 的值。您可能想要的是 "opacity"(小写)。

您的动画正在应用于您创建的新 CALayer...但您似乎从未将该层放入视图中(因此它永远不会被绘制)。更有可能的是,您应该做的是将动画附加到视图的层,并只允许该层为其设置颜色动画。

要将一层添加到另一层,请使用 addSublayer (https://developer.apple.com/reference/quartzcore/calayer/1410833-addsublayer)。您的代码中的视图层应该可以作为 self.view.layer 使用,尽管您可能必须在 viewWillAppear 中而不是在 viewDidLoad

中使用它

您需要在设置动画之前将红色图像视图的 alpha 设置为 0.0

 func pulseAnimation(pulseSpeed: Double) {


    UIView.animate(withDuration: pulseSpeed, delay: 1.0,
                   options: [UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse],
                   animations: {
                    self.red.alpha = 0.5
                    self.red.alpha = 1.0
    }
    )
}

override func viewDidAppear(_ animated: Bool) {

    self.red.alpha = 0.0


    counter.center = CGPoint(x: 185, y: 118)


}