首先創(chuàng)建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)
然后創(chuàng)建一個貝塞爾曲線來描繪物品進入購物車的曲線
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中莫名的打動畫結束的協(xié)議方法了,進去一看原來新加了一個代理
//獲取貝塞爾曲線的路徑
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)
協(xié)議方法:動畫結束后執(zhí)行購物車的抖動
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)
}