加入购物车的抛物线动画, 如图:
抛物线动画(加入购物车效果)直接上代码...
// 这里为了方便调用, 直接写了UIView的扩展.
extension UIView {
/**
加入购物车
- parameter duration: 时间
- parameter endPoint: 终点坐标
- parameter completed: 完成之后的回调
*/
func animateWithStartView(duration duration: NSTimeInterval, endPoint: CGPoint, completed: (Void->Void)? = nil) {
let view = self.copyView()
// 开始坐标
let startX = view.frame.origin.x + view.frame.size.width / 2
let startY = view.frame.origin.y + view.frame.size.height / 2
// 中心点坐标
let centerX = startX + (endPoint.x - startX) / 2
let centerY = startY + (endPoint.y - startY) / 2 - 500
let centerPoint = CGPoint(x: centerX, y: centerY)
// 路径
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: startX, y: startY))
path.addQuadCurveToPoint(endPoint, controlPoint: centerPoint)
// 动画
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = path.CGPath
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.duration = duration
animation.autoreverses = false
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
delay(0.01) {
view.layer.addAnimation(animation, forKey: "ParabolaAnimation")
}
UIView.animateWithDuration(duration, animations: { () -> Void in
var rect = view.frame
rect.size.height = 10
rect.size.width = 10
view.frame = rect
}) { _ in
view.removeFromSuperview()
completed?()
}
}
/**
复制一个view对象
- returns: 赋值得到的新对象
*/
private func copyView() -> UIView {
let view = NSKeyedUnarchiver.unarchiveObjectWithData(NSKeyedArchiver.archivedDataWithRootObject(self))! as! UIView
self.superview?.addSubview(view)
return view
}
/**
延时操作
- parameter duration: 时长(秒)
- parameter completed: 回调
*/
private func delay(duration: NSTimeInterval, completed: ()->Void) {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
completed()
}
}
}
使用
// 终点坐标
let rect = UIScreen.mainScreen().bounds
let endPoint = CGPoint(x: rect.width, y: rect.height)
// 开启动画
imageView.animateWithStartView(duration: 1, endPoint: endPoint)