核心动画

36 阅读1分钟

override  func awakeFromNib() {

        let timer = Timer.init(timeInterval: 2, target: self, selector: #selector(nextPage), userInfo: nil, repeats: true)

        RunLoop.main.add(timer, forMode: RunLoop.Mode.common)

    }

    

    @objc func nextPage() {

        setupAnimation(imageView: animView)

        perform(#selector(setupAnimation), with: animView1,  afterDelay: 1)

        perform(#selector(setupAnimation), with: animView2,  afterDelay: 2)

    }

@objc private func setupAnimation(imageView:UIImageView) {

        let ovalPath = UIBezierPath.init()

        ovalPath.move(to: CGPoint(x: 100, y: 88))

        ovalPath.addCurve(to: CGPoint(x: 120, y: 0), controlPoint1: CGPoint(x: 90, y: 60), controlPoint2: CGPoint(x: 110, y: 30))

        ovalPath.lineWidth = 1.0;

        

        // 创建组动画

        let groupAnimation = CAAnimationGroup()

        groupAnimation.beginTime = CACurrentMediaTime()

        groupAnimation.duration = 2

        groupAnimation.repeatCount = MAXFLOAT

        groupAnimation.isRemovedOnCompletion = false

        

        // 1.缩放效果(创建子动画)

        let scaleDown = CAKeyframeAnimation(keyPath: "transform.scale")

        scaleDown.values = [0.5, 1, 1,  0.9]

        

        // 2.移动

        let move = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))

        move.path = ovalPath.cgPath

        move.calculationMode = .paced

        

        

        // 3.透明度变化效果(创建子动画)

        let fade = CAKeyframeAnimation(keyPath: "opacity")

        fade.values = [0.5,1,1, 0.5]

        // 组合动画(将子动画组合到组动画中)

        groupAnimation.animations = [scaleDown, move,fade]

        

        //添加到view

        imageView.kf.setImage(with: URL(string: array.randomElement() ?? ""))

        imageView.layer.add(groupAnimation, forKey: nil)

}