三个小球上下跳动核心动画


class LiningAnimationView: UIView {

    var objects: [CALayer] = [CALayer(),CALayer(),CALayer()]
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.backgroundColor = .green
        self.addAnimaiton()
    }
    
    func addAnimaiton() {
        let width: CGFloat = 6
        let space: CGFloat = 10
        let amplitude: CGFloat = (self.bounds.size.height - width)
        let duration: CFTimeInterval = 1
        let offset: CGFloat = (self.bounds.size.width - (CGFloat(self.objects.count) * (space + width) - space)) / 2.0
        
        self.objects.enumerated().forEach { (index,item) in
            item.removeAllAnimations()
            let y = index % 2 == 0 ? 0 : amplitude
            item.frame = CGRect(x: offset + (space + width) * CGFloat(index), y: y , width: width, height: width)
            item.cornerRadius = width/2
            item.masksToBounds = true
            
            item.backgroundColor = rgba(68, 159, 232, 1).cgColor
            
            if item.superlayer == nil {
                self.layer.addSublayer(item)
            }
            // 上下跳动的关键帧动画
            let jump = CAKeyframeAnimation(keyPath: "position.y")
            if index % 2 == 0 {
//                低位置
                jump.values = [y, y + amplitude, y] // 在第一、二、三个关键帧位置分别为
            } else {
//                高位置
                jump.values = [y, y - amplitude, y] // 在第一、二、三个关键帧位置分别为
            }
            print("jump.values == \(jump.values) \(self.bounds)")
            jump.keyTimes = [0, 0.5, 1] // 时间百分比
            jump.calculationMode = .paced
            // 动画组合
            let group = CAAnimationGroup()
            group.animations = [jump]
            group.duration = duration // 动画总时长
            group.repeatCount = .infinity // 无限循环
            item.add(group, forKey: nil)
        }
    }
    
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容