收錄: 原文位址
前言
iOS 的動畫架構很成熟,提供必要的資訊,譬如動畫的起始位置與終止位置,動畫效果就出來了
動畫的實作方式挺多的,
有系統提供的簡單 API ,直接提供動畫般的互動效果。
有手動設定互動效果,看起來像是動畫,一般要用到插值。
至于動畫架構,有 UIView 級别的,有功能強勁的 CALayer 級别的動畫。
CALayer 級别的動畫通過靈活設定的 CoreAnimation,CoreAnimation 的正常操作,就是自定義路徑
當然有蘋果推了幾年的 UIViewPropertyAnimator, 動畫可互動性做得比較好;
話不多說;直接來看案例
-
- *
例子一:導航欄動畫
navigationController?.hidesBarsOnSwipe = true
簡單設定
hidesBarsOnSwipe
屬性,就可以了。
該屬性,除了可以調節頭部導航欄,還可以調節底部标簽工具欄
toolbar
例子二:螢幕開鎖效果
一眼看起來有點炫,實際設定很簡單
func openLock() {
UIView.animate(withDuration: 0.4, delay: 1.0, options: [], animations: {
// Rotate keyhole.
self.lockKeyhole.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
}, completion: { _ in
UIView.animate(withDuration: 0.5, delay: 0.2, options: [], animations: {
// Open lock.
let yDelta = self.lockBorder.frame.maxY
self.topLock.center.y -= yDelta
self.lockKeyhole.center.y -= yDelta
self.lockBorder.center.y -= yDelta
self.bottomLock.center.y += yDelta
}, completion: { _ in
self.topLock.removeFromSuperview()
self.lockKeyhole.removeFromSuperview()
self.lockBorder.removeFromSuperview()
self.bottomLock.removeFromSuperview()
})
})
}
總共有四個控件,先讓中間的鎖控件旋轉一下,然後對四個控件,做移位操作
用簡單的關鍵幀動畫,處理要優雅一點
例子三:地圖定位波動
看上去有些眼花的動畫,可以分解為三個動畫
一波未平,一波又起,做一個動畫效果的疊加,就成了動畫的第一幅動畫
一個動畫波動效果,效果用到了透明度的變化,還有範圍的變化
範圍的變化,用的就是 CoreAnimation 的路徑
path
CoreAnimation 簡單設定,就是指明 from 、to,動畫的起始狀态,和動畫終止狀态,然後選擇使用哪一種動畫效果。
動畫的起始狀态,一般是起始位置。簡單的動畫,就是讓他動起來
func sonar(_ beginTime: CFTimeInterval) {
let circlePath1 = UIBezierPath(arcCenter: self.center, radius: CGFloat(3), startAngle: CGFloat(0), endAngle:CGFloat.pi * 2, clockwise: true)
let circlePath2 = UIBezierPath(arcCenter: self.center, radius: CGFloat(80), startAngle: CGFloat(0), endAngle:CGFloat.pi * 2, clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = ColorPalette.green.cgColor
shapeLayer.fillColor = ColorPalette.green.cgColor
shapeLayer.path = circlePath1.cgPath
self.layer.addSublayer(shapeLayer)
// 兩個動畫
let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.fromValue = circlePath1.cgPath
pathAnimation.toValue = circlePath2.cgPath
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 0.8
alphaAnimation.toValue = 0
// 組動畫
let animationGroup = CAAnimationGroup()
animationGroup.beginTime = beginTime
animationGroup.animations = [pathAnimation, alphaAnimation]
// 時間有講究
animationGroup.duration = 2.76
// 不斷重複
animationGroup.repeatCount = Float.greatestFiniteMagnitude
animationGroup.isRemovedOnCompletion = false
animationGroup.fillMode = CAMediaTimingFillMode.forwards
// Add the animation to the layer.
// key 用來 debug
shapeLayer.add(animationGroup, forKey: "sonar")
}
波動效果調用了三次
func startAnimation() {
// 三次動畫,效果合成,
sonar(CACurrentMediaTime())
sonar(CACurrentMediaTime() + 0.92)
sonar(CACurrentMediaTime() + 1.84)
}
例子四:加載動畫
這是 UIView 架構自帶的動畫,看起來不錯,就是做了一個簡單的縮放,通過
transform
屬性做仿射變換
func startAnimation() {
dotOne.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
dotTwo.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
dotThree.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
// 三個不同的 delay, 漸進時間
UIView.animate(withDuration: 0.6, delay: 0.0, options: [.repeat, .autoreverse], animations: {
self.dotOne.transform = CGAffineTransform.identity
}, completion: nil)
UIView.animate(withDuration: 0.6, delay: 0.2, options: [.repeat, .autoreverse], animations: {
self.dotTwo.transform = CGAffineTransform.identity
}, completion: nil)
UIView.animate(withDuration: 0.6, delay: 0.4, options: [.repeat, .autoreverse], animations: {
self.dotThree.transform = CGAffineTransform.identity
}, completion: nil)
}
例子五:下劃線點選轉移動畫
這個也是 UIView 的動畫
動畫的實作效果,是通過更改限制。
限制動畫要注意的是,確定動畫的起始位置準确,起始的時候,一般要調用其父視圖的
layoutIfNeeded
方法,確定視圖的實際位置與限制設定的一緻。
這裡的限制動畫,是通過
NSLayoutAnchor
做得。
一般我們用的是 SnapKit 設定限制,調用也差不多。
func animateContraintsForUnderlineView(_ underlineView: UIView, toSide: Side) {
switch toSide {
case .left:
for constraint in underlineView.superview!.constraints {
if constraint.identifier == ConstraintIdentifiers.centerRightConstraintIdentifier {
constraint.isActive = false
let leftButton = optionsBar.arrangedSubviews[0]
let centerLeftConstraint = underlineView.centerXAnchor.constraint(equalTo: leftButton.centerXAnchor)
centerLeftConstraint.identifier = ConstraintIdentifiers.centerLeftConstraintIdentifier
NSLayoutConstraint.activate([centerLeftConstraint])
}
}
case .right:
for constraint in underlineView.superview!.constraints {
if constraint.identifier == ConstraintIdentifiers.centerLeftConstraintIdentifier {
// 先失效,舊的限制
constraint.isActive = false
// 再建立限制,并激活
let rightButton = optionsBar.arrangedSubviews[1]
let centerRightConstraint = underlineView.centerXAnchor.constraint(equalTo: rightButton.centerXAnchor)
centerRightConstraint.identifier = ConstraintIdentifiers.centerRightConstraintIdentifier
NSLayoutConstraint.activate([centerRightConstraint])
}
}
}
UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: [], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
例子六:清單視圖的頭部拉伸效果
這個沒有用到動畫架構,就是做了一個互動插值
就是補插連續的函數
scrollViewDidScroll
, 及時更新清單視圖頭部的位置、尺寸
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateHeaderView()
}
func updateHeaderView() {
var headerRect = CGRect(x: 0, y: -tableHeaderHeight, width: tableView.bounds.width, height: tableHeaderHeight)
// 決定拉動的方向
if tableView.contentOffset.y < -tableHeaderHeight {
// 就是改 frame
headerRect.origin.y = tableView.contentOffset.y
headerRect.size.height = -tableView.contentOffset.y
}
headerView.frame = headerRect
}
例子七:進度繪制動畫
用到了 CoreAnimation,也用到了插值。
每一段插值都是一個 CoreAnimation 動畫,進度的完成分為多次插值。
這裡動畫效果的主要用到
strokeEnd
屬性, 筆畫結束
插值的時候,要注意,下一段動畫的開始,正是上一段動畫的結束
// 這個用來,主要的效果
let progressLayer = CAShapeLayer()
// 這個用來,附加的顔色
let gradientLayer = CAGradientLayer()
// 給個預設值,外部設定
var range: CGFloat = 128
var curValue: CGFloat = 0 {
didSet {
animateStroke()
}
}
func setupLayers() {
progressLayer.position = CGPoint.zero
progressLayer.lineWidth = 3.0
progressLayer.strokeEnd = 0.0
progressLayer.fillColor = nil
progressLayer.strokeColor = UIColor.black.cgColor
let radius = CGFloat(bounds.height/2) - progressLayer.lineWidth
let startAngle = CGFloat.pi * (-0.5)
let endAngle = CGFloat.pi * 1.5
let width = bounds.width
let height = bounds.height
let modelCenter = CGPoint(x: width / 2, y: height / 2)
let path = UIBezierPath(arcCenter: modelCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
// 指定路徑
progressLayer.path = path.cgPath
layer.addSublayer(progressLayer)
// 有一個漸變
gradientLayer.frame = CGRect(x: 0.0, y: 0.0, width: bounds.width, height: bounds.height)
// teal, 藍綠色
gradientLayer.colors = [ColorPalette.teal.cgColor, ColorPalette.orange.cgColor, ColorPalette.pink.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
gradientLayer.mask = progressLayer // Use progress layer as mask for gradient layer.
layer.addSublayer(gradientLayer)
}
func animateStroke() {
// 前一段的終點
let fromValue = progressLayer.strokeEnd
let toValue = curValue / range
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = fromValue
animation.toValue = toValue
progressLayer.add(animation, forKey: "stroke")
progressLayer.strokeEnd = toValue
}
}
// 動畫路徑,結合插值
例子八:漸變動畫
這個漸變動畫,主要用到了漸變圖層
CAGradientLayer
的
locations
位置屬性,用來調整漸變區域的分布
另一個關鍵點是用了圖層
CALayer
的遮罩
mask
,
簡單了解,把漸變圖層全部蒙起來,隻露出文本的形狀,就是那幾個字母的痕迹
class LoadingLabel: UIView {
let gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
// 灰, 白, 灰
let colors = [UIColor.gray.cgColor, UIColor.white.cgColor, UIColor.gray.cgColor]
gradientLayer.colors = colors
let locations = [0.25, 0.5, 0.75]
gradientLayer.locations = locations as [NSNumber]?
return gradientLayer
}()
// 文字轉圖檔,然後繪制到視圖上
// 通過設定漸變圖層的遮罩 `mask` , 為指定文字,來設定漸變閃爍的效果
@IBInspectable var text: String! {
didSet {
setNeedsDisplay()
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
text.draw(in: bounds, withAttributes: textAttributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// 從文字中,抽取圖檔
let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.clear.cgColor
maskLayer.frame = bounds.offsetBy(dx: bounds.size.width, dy: 0)
maskLayer.contents = image?.cgImage
gradientLayer.mask = maskLayer
}
}
// 設定位置與尺寸
override func layoutSubviews() {
gradientLayer.frame = CGRect(x: -bounds.size.width, y: bounds.origin.y, width: 2 * bounds.size.width, height: bounds.size.height)
}
override func didMoveToWindow() {
super.didMoveToWindow()
layer.addSublayer(gradientLayer)
let gradientAnimation = CABasicAnimation(keyPath: "locations")
gradientAnimation.fromValue = [0.0, 0.0, 0.25]
gradientAnimation.toValue = [0.75, 1.0, 1.0]
gradientAnimation.duration = 1.7
// 一直循環
gradientAnimation.repeatCount = Float.infinity
gradientAnimation.isRemovedOnCompletion = false
gradientAnimation.fillMode = CAMediaTimingFillMode.forwards
gradientLayer.add(gradientAnimation, forKey: nil)
}
}
例子九:下拉重新整理動畫
首先通過方法
scrollViewDidScroll
和
scrollViewWillEndDragging
做插值
extension PullRefreshView: UIScrollViewDelegate{
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = CGFloat(max(-(scrollView.contentOffset.y + scrollView.contentInset.top), 0.0))
self.progress = min(max(offsetY / frame.size.height, 0.0), 1.0)
// 做互斥的狀态管理
if !isRefreshing {
redrawFromProgress(self.progress)
}
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if !isRefreshing && self.progress >= 1.0 {
delegate?.PullRefreshViewDidRefresh(self)
beginRefreshing()
}
}
}
畫面中飛碟動來動去,是通過
CAKeyframeAnimation(keyPath: "position")
,關鍵幀動畫的位置屬性,設定的
func redrawFromProgress(_ progress: CGFloat) {
/* PART 1 ENTER ANIMATION */
let enterPath = paths.start
// 動畫指定路徑走
let pathAnimation = CAKeyframeAnimation(keyPath: "position")
pathAnimation.path = enterPath.cgPath
pathAnimation.calculationMode = CAAnimationCalculationMode.paced
pathAnimation.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)]
pathAnimation.beginTime = 1e-100
pathAnimation.duration = 1.0
pathAnimation.timeOffset = CFTimeInterval() + Double(progress)
pathAnimation.isRemovedOnCompletion = false
pathAnimation.fillMode = CAMediaTimingFillMode.forwards
flyingSaucerLayer.add(pathAnimation, forKey: nil)
flyingSaucerLayer.position = enterPath.currentPoint
let sizeAlongEnterPathAnimation = CABasicAnimation(keyPath: "transform.scale")
sizeAlongEnterPathAnimation.fromValue = 0
sizeAlongEnterPathAnimation.toValue = progress
sizeAlongEnterPathAnimation.beginTime = 1e-100
sizeAlongEnterPathAnimation.duration = 1.0
sizeAlongEnterPathAnimation.isRemovedOnCompletion = false
sizeAlongEnterPathAnimation.fillMode = CAMediaTimingFillMode.forwards
flyingSaucerLayer.add(sizeAlongEnterPathAnimation, forKey: nil)
}
// 設定路徑
func customPaths(frame: CGRect = CGRect(x: 4, y: 3, width: 166, height: 74)) -> ( UIBezierPath, UIBezierPath) {
// 兩條路徑
let startY = 0.09459 * frame.height
let enterPath = UIBezierPath()
// ...
enterPath.addCurve(to: CGPoint(x: frame.minX + 0.21694 * frame.width, y: frame.minY + 0.85855 * frame.height), controlPoint1: CGPoint(x: frame.minX + 0.04828 * frame.width, y: frame.minY + 0.68225 * frame.height), controlPoint2: CGPoint(x: frame.minX + 0.21694 * frame.width, y: frame.minY + 0.85855 * frame.height))
enterPath.addCurve(to: CGPoint(x: frame.minX + 0.36994 * frame.width, y: frame.minY + 0.92990 * frame.height), controlPoint1: CGPoint(x: frame.minX + 0.21694 * frame.width, y: frame.minY + 0.85855 * frame.height), controlPoint2: CGPoint(x: frame.minX + 0.33123 * frame.width, y: frame.minY + 0.93830 * frame.height))
// ...
enterPath.usesEvenOddFillRule = true
let exitPath = UIBezierPath()
exitPath.move(to: CGPoint(x: frame.minX + 0.98193 * frame.width, y: frame.minY + 0.15336 * frame.height))
exitPath.addLine(to: CGPoint(x: frame.minX + 0.51372 * frame.width, y: frame.minY + 0.28558 * frame.height))
// ...
exitPath.miterLimit = 4
exitPath.usesEvenOddFillRule = true
return (enterPath, exitPath)
}
}
這個動畫比較複雜,需要做大量的數學計算,還要調試,具體看文尾的 git repo.
一般這種動畫,我們用
Lottie
例子十:文本變換動畫
這個動畫有些複雜,重點使用了 CoreAnimation 的組動畫,疊加了五種效果,縮放、尺寸、布局、位置與透明度。
具體看文尾的 git repo.
class func animation(_ layer: CALayer, duration: TimeInterval, delay: TimeInterval, animations: (() -> ())?, completion: ((_ finished: Bool)-> ())?) {
let animation = CLMLayerAnimation()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
var animationGroup: CAAnimationGroup?
let oldLayer = self.animatableLayerCopy(layer)
animation.completionClosure = completion
if let layerAnimations = animations {
CATransaction.begin()
CATransaction.setDisableActions(true)
layerAnimations()
CATransaction.commit()
}
animationGroup = groupAnimationsForDifferences(oldLayer, newLayer: layer)
if let differenceAnimation = animationGroup {
differenceAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
differenceAnimation.duration = duration
differenceAnimation.beginTime = CACurrentMediaTime()
layer.add(differenceAnimation, forKey: nil)
}
else {
if let completion = animation.completionClosure {
completion(true)
}
}
}
}
class func groupAnimationsForDifferences(_ oldLayer: CALayer, newLayer: CALayer) -> CAAnimationGroup? {
var animationGroup: CAAnimationGroup?
var animations = [CABasicAnimation]()
// 疊加了五種效果
if !CATransform3DEqualToTransform(oldLayer.transform, newLayer.transform) {
let animation = CABasicAnimation(keyPath: "transform")
animation.fromValue = NSValue(caTransform3D: oldLayer.transform)
animation.toValue = NSValue(caTransform3D: newLayer.transform)
animations.append(animation)
}
if !oldLayer.bounds.equalTo(newLayer.bounds) {
let animation = CABasicAnimation(keyPath: "bounds")
animation.fromValue = NSValue(cgRect: oldLayer.bounds)
animation.toValue = NSValue(cgRect: newLayer.bounds)
animations.append(animation)
}
if !oldLayer.frame.equalTo(newLayer.frame) {
let animation = CABasicAnimation(keyPath: "frame")
animation.fromValue = NSValue(cgRect: oldLayer.frame)
animation.toValue = NSValue(cgRect: newLayer.frame)
animations.append(animation)
}
if !oldLayer.position.equalTo(newLayer.position) {
let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = NSValue(cgPoint: oldLayer.position)
animation.toValue = NSValue(cgPoint: newLayer.position)
animations.append(animation)
}
if oldLayer.opacity != newLayer.opacity {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = oldLayer.opacity
animation.toValue = newLayer.opacity
animations.append(animation)
}
if animations.count > 0 {
animationGroup = CAAnimationGroup()
animationGroup!.animations = animations
}
return animationGroup
}
例子十一:動态圖動畫
從 gif 檔案裡面取出每桢圖檔,算出持續時間,設定動畫圖檔
internal class func animatedImageWithSource(_ source: CGImageSource) -> UIImage? {
// 需要喂圖檔,
// 喂動畫持續時間
let count = CGImageSourceGetCount(source)
var data: (images: [CGImage], delays: [Int]) = ([CGImage](), [Int]())
// Fill arrays
for i in 0..<count {
// Add image
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
data.images.append(image)
}
let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
source: source)
data.delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
}
// Calculate full duration
let duration: Int = {
var sum = 0
for val: Int in data.delays {
sum += val
}
return sum
}()
let gcd = gcdForArray(data.delays)
var frames = [UIImage]()
var frame: UIImage
var frameCount: Int
for i in 0..<count {
frame = UIImage(cgImage: data.images[Int(i)])
frameCount = Int(data.delays[Int(i)] / gcd)
for _ in 0..<frameCount {
frames.append(frame)
}
}
let animation = UIImage.animatedImage(with: frames,
duration: Double(duration) / 1000.0)
return animation
}