Core Animation 是苹果提供的动画和视觉效果框架。我们可以使用它来为 IOS App 添加平滑的动画和互动效果。
使用 Core Animation 的基本步骤:
- 添加 CALayer 作为基本的动画目标,或者作为 UIView 的 layer 属性获取其层。
- 设置 CALayer 的属性如背景颜色、边框、位置、透明度等初始值。
- 创建 CABasicAnimation 或 CAKeyframeAnimation 对象来定义动画。
- 设置动画的属性如持续时间、起止值、缓动函数等。
- 将动画添加到 CALayer 的 animations 数组中。
- 使用 CALayer 的 frame 属性获取或设置其位置和大小。
- 为动画设置 timingCurve 来自定义缓动函数。
- 使用 wk_animate(withDuration:animations:) 方法来执行动画。
- 设置 animationDidStop 的回调方法来获取动画结束的通知。
下面是一个简单的 Core Animation 示例:
swift
let view = UIView()
view.backgroundColor = .red
view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let layer = view.layer
let animate = CABasicAnimation(keyPath: "position")
animate.fromValue = CGPoint(x: 0, y: 0)
animate.toValue = CGPoint(x: 200, y: 200)
animate.duration = 2.0
layer.add(animate, forKey: nil)
layer.position = CGPoint(x: 200, y: 200)
animate.timingCurve = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animate.fromValue = layer.position
animate.toValue = CGPoint(x: 0, y: 0)
layer.add(animate, forKey: nil)