iOS 的動畫框架很成熟,提供必要的信息,譬如動畫的起始位置與終止位置,動畫效果就出來了git
動畫的實現方式挺多的,github
有系統提供的簡單 API ,直接提供動畫般的交互效果。bash
至於動畫框架,有 UIView 級別的,有功能強勁的 CALayer 級別的動畫。app
固然有蘋果推了幾年的 UIViewPropertyAnimator, 動畫可交互性作得比較好框架
navigationController?.hidesBarsOnSwipe = true
複製代碼
簡單設置 hidesBarsOnSwipe
屬性,就能夠了。async
該屬性,除了能夠調節頭部導航欄,還能夠調節底部標籤工具欄 toolbar
ide
一眼看起來有點炫,實際設置很簡單函數
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
}
複製代碼