-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
HeroCoreAnimationViewContext.swift
416 lines (367 loc) · 15 KB
/
HeroCoreAnimationViewContext.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <me@lkzhao.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension CALayer {
internal static var heroAddedAnimations: [(CALayer, String, CAAnimation)]? = {
let swizzling: (AnyClass, Selector, Selector) -> Void = { forClass, originalSelector, swizzledSelector in
if let originalMethod = class_getInstanceMethod(forClass, originalSelector), let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
let originalSelector = #selector(add(_:forKey:))
let swizzledSelector = #selector(hero_add(anim:forKey:))
swizzling(CALayer.self, originalSelector, swizzledSelector)
return nil
}()
@objc dynamic func hero_add(anim: CAAnimation, forKey: String?) {
let copiedAnim = anim.copy() as! CAAnimation
copiedAnim.delegate = nil // having delegate resulted some weird animation behavior
CALayer.heroAddedAnimations?.append((self, forKey!, copiedAnim))
hero_add(anim: anim, forKey: forKey)
}
}
internal class HeroCoreAnimationViewContext: HeroAnimatorViewContext {
var state = [String: (Any?, Any?)]()
var timingFunction: CAMediaTimingFunction = .standard
var animations: [(CALayer, String, CAAnimation)] = []
// computed
var contentLayer: CALayer? {
return snapshot.layer.sublayers?.get(0)
}
var overlayLayer: CALayer?
override class func canAnimate(view: UIView, state: HeroTargetState, appearing: Bool) -> Bool {
return state.position != nil ||
state.size != nil ||
state.transform != nil ||
state.cornerRadius != nil ||
state.opacity != nil ||
state.overlay != nil ||
state.backgroundColor != nil ||
state.borderColor != nil ||
state.borderWidth != nil ||
state.shadowOpacity != nil ||
state.shadowRadius != nil ||
state.shadowOffset != nil ||
state.shadowColor != nil ||
state.shadowPath != nil ||
state.contentsRect != nil ||
state.forceAnimate
}
func getOverlayLayer() -> CALayer {
if overlayLayer == nil {
overlayLayer = CALayer()
overlayLayer!.frame = snapshot.bounds
overlayLayer!.opacity = 0
snapshot.layer.addSublayer(overlayLayer!)
}
return overlayLayer!
}
func overlayKeyFor(key: String) -> String? {
if key.hasPrefix("overlay.") {
var key = key
key.removeSubrange(key.startIndex..<key.index(key.startIndex, offsetBy: 8))
return key
}
return nil
}
func currentValue(key: String) -> Any? {
if let key = overlayKeyFor(key: key) {
return (overlayLayer?.presentation() ?? overlayLayer)?.value(forKeyPath: key)
}
if snapshot.layer.animationKeys()?.isEmpty != false {
return snapshot.layer.value(forKeyPath: key)
}
return (snapshot.layer.presentation() ?? snapshot.layer).value(forKeyPath: key)
}
func getAnimation(key: String, beginTime: TimeInterval, duration: TimeInterval, fromValue: Any?, toValue: Any?, ignoreArc: Bool = false) -> CAPropertyAnimation {
let key = overlayKeyFor(key: key) ?? key
let anim: CAPropertyAnimation
if !ignoreArc, key == "position", let arcIntensity = targetState.arc,
let fromPos = (fromValue as? NSValue)?.cgPointValue,
let toPos = (toValue as? NSValue)?.cgPointValue,
abs(fromPos.x - toPos.x) >= 1, abs(fromPos.y - toPos.y) >= 1 {
let kanim = CAKeyframeAnimation(keyPath: key)
let path = CGMutablePath()
let maxControl = fromPos.y > toPos.y ? CGPoint(x: toPos.x, y: fromPos.y) : CGPoint(x: fromPos.x, y: toPos.y)
let minControl = (toPos - fromPos) / 2 + fromPos
path.move(to: fromPos)
path.addQuadCurve(to: toPos, control: minControl + (maxControl - minControl) * arcIntensity)
kanim.values = [fromValue!, toValue!]
kanim.path = path
kanim.duration = duration
kanim.timingFunctions = [timingFunction]
anim = kanim
} else if #available(iOS 9.0, *), key != "cornerRadius", let (stiffness, damping) = targetState.spring {
let sanim = CASpringAnimation(keyPath: key)
sanim.stiffness = stiffness
sanim.damping = damping
sanim.duration = sanim.settlingDuration
sanim.fromValue = fromValue
sanim.toValue = toValue
anim = sanim
} else {
let banim = CABasicAnimation(keyPath: key)
banim.duration = duration
banim.fromValue = fromValue
banim.toValue = toValue
banim.timingFunction = timingFunction
anim = banim
}
anim.fillMode = kCAFillModeBoth
anim.isRemovedOnCompletion = false
anim.beginTime = beginTime
return anim
}
func setSize(view: UIView, newSize: CGSize) {
let oldSize = view.bounds.size
if targetState.snapshotType != .noSnapshot {
for subview in view.subviews {
let center = subview.center
let size = subview.bounds.size
subview.center = CGPoint(x: center.x / oldSize.width * newSize.width, y: center.y / oldSize.height * newSize.height)
subview.bounds.size = size / oldSize * newSize
setSize(view: subview, newSize: size / oldSize * newSize)
}
view.bounds.size = newSize
} else {
view.bounds.size = newSize
view.layoutSubviews()
}
}
func uiViewBasedAnimate(duration: TimeInterval, delay: TimeInterval, _ animations: @escaping () -> Void) {
CALayer.heroAddedAnimations = []
if let (stiffness, damping) = targetState.spring {
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: animations, completion: nil)
let addedAnimations = CALayer.heroAddedAnimations!
CALayer.heroAddedAnimations = nil
for (layer, key, anim) in addedAnimations {
if #available(iOS 9.0, *), let anim = anim as? CASpringAnimation {
anim.stiffness = stiffness
anim.damping = damping
self.addAnimation(anim, for: key, to: layer)
} else {
self.animations.append((layer, key, anim))
}
}
} else {
CATransaction.begin()
CATransaction.setAnimationTimingFunction(timingFunction)
UIView.animate(withDuration: duration, delay: delay, options: [], animations: animations, completion: nil)
CATransaction.commit()
let addedAnimations = CALayer.heroAddedAnimations!
CALayer.heroAddedAnimations = nil
self.animations.append(contentsOf: addedAnimations)
}
}
func addAnimation(_ animation: CAAnimation, for key: String, to layer: CALayer) {
animations.append((layer, key, animation))
layer.add(animation, forKey: key)
}
// return the completion duration of the animation (duration + initial delay, not counting the beginTime)
func animate(key: String, beginTime: TimeInterval, duration: TimeInterval, fromValue: Any?, toValue: Any?) -> TimeInterval {
let anim = getAnimation(key: key, beginTime: beginTime, duration: duration, fromValue: fromValue, toValue: toValue)
if let overlayKey = overlayKeyFor(key: key) {
addAnimation(anim, for: overlayKey, to: getOverlayLayer())
} else {
switch key {
case "cornerRadius", "contentsRect", "contentsScale":
addAnimation(anim, for: key, to: snapshot.layer)
if let contentLayer = contentLayer {
addAnimation(anim.copy() as! CAAnimation, for: key, to: contentLayer)
}
if let overlayLayer = overlayLayer {
addAnimation(anim.copy() as! CAAnimation, for: key, to: overlayLayer)
}
case "bounds.size":
let fromSize = (fromValue as? NSValue)!.cgSizeValue
let toSize = (toValue as? NSValue)!.cgSizeValue
setSize(view: snapshot, newSize: fromSize)
uiViewBasedAnimate(duration: anim.duration, delay: beginTime - currentTime) {
self.setSize(view: self.snapshot, newSize: toSize)
}
default:
addAnimation(anim, for: key, to: snapshot.layer)
}
}
return anim.duration + anim.beginTime - beginTime
}
/**
- Returns: a CALayer [keyPath:value] map for animation
*/
func viewState(targetState: HeroTargetState) -> [String: Any?] {
var targetState = targetState
var rtn = [String: Any?]()
if let size = targetState.size {
if targetState.useScaleBasedSizeChange ?? self.targetState.useScaleBasedSizeChange ?? false {
let currentSize = snapshot.bounds.size
targetState.append(.scale(x:size.width / currentSize.width,
y:size.height / currentSize.height))
} else {
rtn["bounds.size"] = NSValue(cgSize: size)
}
}
if let position = targetState.position {
rtn["position"] = NSValue(cgPoint: position)
}
if let opacity = targetState.opacity, !(snapshot is UIVisualEffectView) {
rtn["opacity"] = NSNumber(value: opacity)
}
if let cornerRadius = targetState.cornerRadius {
rtn["cornerRadius"] = NSNumber(value: cornerRadius.native)
}
if let backgroundColor = targetState.backgroundColor {
rtn["backgroundColor"] = backgroundColor
}
if let zPosition = targetState.zPosition {
rtn["zPosition"] = NSNumber(value: zPosition.native)
}
if let borderWidth = targetState.borderWidth {
rtn["borderWidth"] = NSNumber(value: borderWidth.native)
}
if let borderColor = targetState.borderColor {
rtn["borderColor"] = borderColor
}
if let masksToBounds = targetState.masksToBounds {
rtn["masksToBounds"] = masksToBounds
}
if targetState.displayShadow {
if let shadowColor = targetState.shadowColor {
rtn["shadowColor"] = shadowColor
}
if let shadowRadius = targetState.shadowRadius {
rtn["shadowRadius"] = NSNumber(value: shadowRadius.native)
}
if let shadowOpacity = targetState.shadowOpacity {
rtn["shadowOpacity"] = NSNumber(value: shadowOpacity)
}
if let shadowPath = targetState.shadowPath {
rtn["shadowPath"] = shadowPath
}
if let shadowOffset = targetState.shadowOffset {
rtn["shadowOffset"] = NSValue(cgSize: shadowOffset)
}
}
if let contentsRect = targetState.contentsRect {
rtn["contentsRect"] = NSValue(cgRect: contentsRect)
}
if let contentsScale = targetState.contentsScale {
rtn["contentsScale"] = NSNumber(value: contentsScale.native)
}
if let transform = targetState.transform {
rtn["transform"] = NSValue(caTransform3D: transform)
}
if let (color, opacity) = targetState.overlay {
rtn["overlay.backgroundColor"] = color
rtn["overlay.opacity"] = NSNumber(value: opacity.native)
}
return rtn
}
override func apply(state: HeroTargetState) {
let targetState = viewState(targetState: state)
for (key, targetValue) in targetState {
if self.state[key] == nil {
let current = currentValue(key: key)
self.state[key] = (current, current)
}
let oldAnimations = animations
animations = []
_ = animate(key: key, beginTime: 0, duration: 100, fromValue: targetValue, toValue: targetValue)
animations = oldAnimations
}
}
override func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval {
for (key, (fromValue, toValue)) in state {
let realToValue = !reverse ? toValue : fromValue
let realFromValue = currentValue(key: key)
state[key] = (realFromValue, realToValue)
}
if reverse {
if timePassed > targetState.delay + duration {
let backDelay = timePassed - (targetState.delay + duration)
return animate(delay: backDelay, duration: duration)
} else if timePassed > targetState.delay {
return animate(delay: 0, duration: duration - (timePassed - targetState.delay))
} else {
return 0
}
} else {
if timePassed <= targetState.delay {
return animate(delay: targetState.delay - timePassed, duration: duration)
} else if timePassed <= targetState.delay + duration {
let timePassedDelay = timePassed - targetState.delay
return animate(delay: 0, duration: duration - timePassedDelay)
} else {
return 0
}
}
}
func animate(delay: TimeInterval, duration: TimeInterval) -> TimeInterval {
for (layer, key, _) in animations {
layer.removeAnimation(forKey: key)
}
if let tf = targetState.timingFunction {
timingFunction = tf
}
var timeUntilStop: TimeInterval = duration
animations = []
for (key, (fromValue, toValue)) in state {
let neededTime = animate(key: key, beginTime: currentTime + delay, duration: duration, fromValue: fromValue, toValue: toValue)
timeUntilStop = max(timeUntilStop, neededTime)
}
return timeUntilStop + delay
}
override func seek(timePassed: TimeInterval) {
let timeOffset = timePassed - targetState.delay
for (layer, key, anim) in animations {
anim.speed = 0
anim.timeOffset = max(0.01, min(anim.duration - 0.01, timeOffset))
layer.removeAnimation(forKey: key)
layer.add(anim, forKey: key)
}
}
override func clean() {
super.clean()
overlayLayer = nil
}
override func startAnimations() -> TimeInterval {
if let beginStateModifiers = targetState.beginState {
let beginState = HeroTargetState(modifiers: beginStateModifiers)
let appeared = viewState(targetState: beginState)
for (key, value) in appeared {
snapshot.layer.setValue(value, forKeyPath: key)
}
if let (color, opacity) = beginState.overlay {
let overlay = getOverlayLayer()
overlay.backgroundColor = color
overlay.opacity = Float(opacity)
}
}
let disappeared = viewState(targetState: targetState)
for (key, disappearedState) in disappeared {
let appearingState = currentValue(key: key)
let toValue = appearing ? appearingState : disappearedState
let fromValue = !appearing ? appearingState : disappearedState
state[key] = (fromValue, toValue)
}
return animate(delay: targetState.delay, duration: duration)
}
}