Swift 3.0 物品加入购物车的抛物线动画

加入购物车动画.gif

首先创建2个图片和一个按钮

        let btn = UIButton.init(frame: CGRect.init(x: 100, y: 50, width: 50, height: 20))
        btn.setTitle("购买", for: .normal)
        btn.backgroundColor = UIColor.orange
        btn.addTarget(self, action: #selector(butBtnClick), for: .touchUpInside)
        self.view.addSubview(btn)
        
        
        goodImage.frame = CGRect.init(x: 20, y: 100, width: 30, height: 30)
        goodImage.image = UIImage.init(named: "商品")
        self.view.addSubview(goodImage)
        
        buyCar.frame = CGRect.init(x: 300, y: 300, width: 30, height: 30)
        buyCar.image = UIImage.init(named: "购物车")
        self.view.addSubview(buyCar)

然后创建一个贝塞尔曲线来描绘物品进入购物车的曲线

        path.move(to: CGPoint.init(x:20,y:100))
        path.addQuadCurve(to: CGPoint.init(x: 300, y: 300), controlPoint: CGPoint.init(x: 150, y: 20))

然后在按钮的点击事件中使用组合动画: 获取贝塞尔的路径,旋转动画,缩小动画
最后的组合动画方法添加了一个代理,OC中是不需要的,不知道Swift中莫名的打动画结束的协议方法了,进去一看原来新加了一个代理

        //获取贝塞尔曲线的路径
        let animationPath = CAKeyframeAnimation.init(keyPath: "position")
        animationPath.path = path.cgPath
        animationPath.rotationMode = kCAAnimationRotateAuto
        
        
        //旋转
        let rotate:CABasicAnimation = CABasicAnimation()
        rotate.keyPath = "transform.rotation"
        rotate.toValue = M_PI
        
        //缩小图片到0
        let scale:CABasicAnimation = CABasicAnimation()
        scale.keyPath = "transform.scale"
        scale.toValue = 0.0

        //组合动画
        let animationGroup:CAAnimationGroup = CAAnimationGroup()
        animationGroup.animations = [animationPath,rotate,scale];
        animationGroup.duration = 2.0;
        animationGroup.delegate = self
        animationGroup.fillMode = kCAFillModeForwards;
        animationGroup.isRemovedOnCompletion = false
        goodImage.layer.add(animationGroup, forKey:
            nil)


协议方法:动画结束后执行购物车的抖动

    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        //购物车抖动
        let shakeAnimation = CABasicAnimation.init(keyPath: "transform.translation.y")
        shakeAnimation.duration = 0.5
        shakeAnimation.fromValue = NSNumber.init(value: -5)
        shakeAnimation.toValue = NSNumber.init(value: 5)
        shakeAnimation.autoreverses = true
        buyCar.layer.add(shakeAnimation, forKey: nil)
    }

你可能感兴趣的:(Swift 3.0 物品加入购物车的抛物线动画)