LOTAnimationView.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. //
  2. // LOTAnimationView
  3. // LottieAnimator
  4. //
  5. // Created by Brandon Withrow on 12/14/15.
  6. // Copyright © 2015 Brandon Withrow. All rights reserved.
  7. //
  8. #import "LOTAnimationView.h"
  9. #import "LOTPlatformCompat.h"
  10. #import "LOTModels.h"
  11. #import "LOTHelpers.h"
  12. #import "LOTAnimationView_Internal.h"
  13. #import "LOTAnimationCache.h"
  14. #import "LOTCompositionContainer.h"
  15. static NSString * const kCompContainerAnimationKey = @"play";
  16. @implementation LOTAnimationView {
  17. LOTCompositionContainer *_compContainer;
  18. NSNumber *_playRangeStartFrame;
  19. NSNumber *_playRangeEndFrame;
  20. CGFloat _playRangeStartProgress;
  21. CGFloat _playRangeEndProgress;
  22. NSBundle *_bundle;
  23. CGFloat _animationProgress;
  24. // Properties for tracking automatic restoration of animation.
  25. BOOL _shouldRestoreStateWhenAttachedToWindow;
  26. LOTAnimationCompletionBlock _completionBlockToRestoreWhenAttachedToWindow;
  27. }
  28. # pragma mark - Convenience Initializers
  29. + (nonnull instancetype)animationNamed:(nonnull NSString *)animationName {
  30. return [self animationNamed:animationName inBundle:[NSBundle mainBundle]];
  31. }
  32. + (nonnull instancetype)animationNamed:(nonnull NSString *)animationName inBundle:(nonnull NSBundle *)bundle {
  33. LOTComposition *comp = [LOTComposition animationNamed:animationName inBundle:bundle];
  34. return [[self alloc] initWithModel:comp inBundle:bundle];
  35. }
  36. + (nonnull instancetype)animationFromJSON:(nonnull NSDictionary *)animationJSON {
  37. return [self animationFromJSON:animationJSON inBundle:[NSBundle mainBundle]];
  38. }
  39. + (nonnull instancetype)animationFromJSON:(nullable NSDictionary *)animationJSON inBundle:(nullable NSBundle *)bundle {
  40. LOTComposition *comp = [LOTComposition animationFromJSON:animationJSON inBundle:bundle];
  41. return [[self alloc] initWithModel:comp inBundle:bundle];
  42. }
  43. + (nonnull instancetype)animationWithFilePath:(nonnull NSString *)filePath {
  44. LOTComposition *comp = [LOTComposition animationWithFilePath:filePath];
  45. return [[self alloc] initWithModel:comp inBundle:[NSBundle mainBundle]];
  46. }
  47. # pragma mark - Initializers
  48. - (instancetype)initWithContentsOfURL:(NSURL *)url {
  49. self = [self initWithFrame:CGRectZero];
  50. if (self) {
  51. LOTComposition *laScene = [[LOTAnimationCache sharedCache] animationForKey:url.absoluteString];
  52. if (laScene) {
  53. laScene.cacheKey = url.absoluteString;
  54. [self _initializeAnimationContainer];
  55. [self _setupWithSceneModel:laScene];
  56. } else {
  57. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  58. NSData *animationData = [NSData dataWithContentsOfURL:url];
  59. if (!animationData) {
  60. return;
  61. }
  62. NSError *error;
  63. NSDictionary *animationJSON = [NSJSONSerialization JSONObjectWithData:animationData
  64. options:0 error:&error];
  65. if (error || !animationJSON) {
  66. return;
  67. }
  68. LOTComposition *laScene = [[LOTComposition alloc] initWithJSON:animationJSON withAssetBundle:[NSBundle mainBundle]];
  69. dispatch_async(dispatch_get_main_queue(), ^(void) {
  70. [[LOTAnimationCache sharedCache] addAnimation:laScene forKey:url.absoluteString];
  71. laScene.cacheKey = url.absoluteString;
  72. [self _initializeAnimationContainer];
  73. [self _setupWithSceneModel:laScene];
  74. });
  75. });
  76. }
  77. }
  78. return self;
  79. }
  80. - (instancetype)initWithModel:(LOTComposition *)model inBundle:(NSBundle *)bundle {
  81. self = [self initWithFrame:model.compBounds];
  82. if (self) {
  83. _bundle = bundle;
  84. [self _initializeAnimationContainer];
  85. [self _setupWithSceneModel:model];
  86. }
  87. return self;
  88. }
  89. - (instancetype)initWithFrame:(CGRect)frame {
  90. self = [super initWithFrame:frame];
  91. if (self) {
  92. [self _commonInit];
  93. }
  94. return self;
  95. }
  96. - (instancetype)initWithCoder:(NSCoder *)coder {
  97. self = [super initWithCoder:coder];
  98. if (self) {
  99. [self _commonInit];
  100. }
  101. return self;
  102. }
  103. # pragma mark - Inspectables
  104. - (void)setAnimation:(NSString *)animationName {
  105. _animation = animationName;
  106. [self setAnimationNamed:animationName];
  107. }
  108. # pragma mark - Internal Methods
  109. #if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
  110. - (void)_initializeAnimationContainer {
  111. self.clipsToBounds = YES;
  112. }
  113. - (void)_commonInit {
  114. _animationSpeed = 1;
  115. _animationProgress = 0;
  116. _loopAnimation = NO;
  117. _autoReverseAnimation = NO;
  118. _playRangeEndFrame = nil;
  119. _playRangeStartFrame = nil;
  120. _playRangeEndProgress = 0;
  121. _playRangeStartProgress = 0;
  122. _shouldRasterizeWhenIdle = NO;
  123. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(_handleWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
  124. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(_handleWillEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
  125. }
  126. #else
  127. - (void)_initializeAnimationContainer {
  128. self.wantsLayer = YES;
  129. }
  130. - (void)_commonInit {
  131. _animationSpeed = 1;
  132. _animationProgress = 0;
  133. _loopAnimation = NO;
  134. _autoReverseAnimation = NO;
  135. _playRangeEndFrame = nil;
  136. _playRangeStartFrame = nil;
  137. _playRangeEndProgress = 0;
  138. _playRangeStartProgress = 0;
  139. _shouldRasterizeWhenIdle = NO;
  140. }
  141. #endif
  142. - (void)dealloc {
  143. [NSNotificationCenter.defaultCenter removeObserver:self];
  144. }
  145. - (void)_setupWithSceneModel:(LOTComposition *)model {
  146. if (_sceneModel) {
  147. [self _removeCurrentAnimationIfNecessary];
  148. [self _callCompletionIfNecessary:NO];
  149. [_compContainer removeFromSuperlayer];
  150. _compContainer = nil;
  151. _sceneModel = nil;
  152. [self _commonInit];
  153. }
  154. _sceneModel = model;
  155. _compContainer = [[LOTCompositionContainer alloc] initWithModel:nil inLayerGroup:nil withLayerGroup:_sceneModel.layerGroup withAssestGroup:_sceneModel.assetGroup];
  156. [self.layer addSublayer:_compContainer];
  157. [self _restoreState];
  158. [self setNeedsLayout];
  159. }
  160. - (void)_restoreState {
  161. if (_isAnimationPlaying) {
  162. _isAnimationPlaying = NO;
  163. if (_playRangeStartFrame && _playRangeEndFrame) {
  164. [self playFromFrame:_playRangeStartFrame toFrame:_playRangeEndFrame withCompletion:self.completionBlock];
  165. } else if (_playRangeEndProgress != _playRangeStartProgress) {
  166. [self playFromProgress:_playRangeStartProgress toProgress:_playRangeEndProgress withCompletion:self.completionBlock];
  167. } else {
  168. [self playWithCompletion:self.completionBlock];
  169. }
  170. } else {
  171. self.animationProgress = _animationProgress;
  172. }
  173. }
  174. - (void)_removeCurrentAnimationIfNecessary {
  175. _isAnimationPlaying = NO;
  176. [_compContainer removeAllAnimations];
  177. _compContainer.shouldRasterize = _shouldRasterizeWhenIdle;
  178. }
  179. - (CGFloat)_progressForFrame:(NSNumber *)frame {
  180. if (!_sceneModel) {
  181. return 0;
  182. }
  183. return ((frame.floatValue - _sceneModel.startFrame.floatValue) / (_sceneModel.endFrame.floatValue - _sceneModel.startFrame.floatValue));
  184. }
  185. - (NSNumber *)_frameForProgress:(CGFloat)progress {
  186. if (!_sceneModel) {
  187. return @0;
  188. }
  189. return @(((_sceneModel.endFrame.floatValue - _sceneModel.startFrame.floatValue) * progress) + _sceneModel.startFrame.floatValue);
  190. }
  191. - (BOOL)_isSpeedNegative {
  192. // If the animation speed is negative, then we're moving backwards.
  193. return _animationSpeed >= 0;
  194. }
  195. - (void)_handleWindowChanges:(BOOL)hasNewWindow
  196. {
  197. // When this view or its superview is leaving the screen, e.g. a modal is presented or another
  198. // screen is pushed, this method will get called with newWindow value set to nil - indicating that
  199. // this view will be detached from the visible window.
  200. // When a view is detached, animations will stop - but will not automatically resumed when it's
  201. // re-attached back to window, e.g. when the presented modal is dismissed or another screen is
  202. // pop.
  203. if (hasNewWindow) {
  204. // The view is being re-attached, resume animation if needed.
  205. if (_shouldRestoreStateWhenAttachedToWindow) {
  206. _shouldRestoreStateWhenAttachedToWindow = NO;
  207. _isAnimationPlaying = YES;
  208. _completionBlock = _completionBlockToRestoreWhenAttachedToWindow;
  209. _completionBlockToRestoreWhenAttachedToWindow = nil;
  210. [self performSelector:@selector(_restoreState) withObject:nil afterDelay:0 inModes:@[NSRunLoopCommonModes]];
  211. }
  212. } else {
  213. // The view is being detached, capture information that need to be restored later.
  214. if (_isAnimationPlaying) {
  215. LOTAnimationCompletionBlock completion = _completionBlock;
  216. [self pause];
  217. _shouldRestoreStateWhenAttachedToWindow = YES;
  218. _completionBlockToRestoreWhenAttachedToWindow = completion;
  219. _completionBlock = nil;
  220. }
  221. }
  222. }
  223. - (void)_handleWillEnterBackground {
  224. [self _handleWindowChanges: false];
  225. }
  226. - (void)_handleWillEnterForeground {
  227. [self _handleWindowChanges: (self.window != nil)];
  228. }
  229. # pragma mark - Completion Block
  230. - (void)_callCompletionIfNecessary:(BOOL)complete {
  231. if (self.completionBlock) {
  232. LOTAnimationCompletionBlock completion = self.completionBlock;
  233. self.completionBlock = nil;
  234. completion(complete);
  235. }
  236. }
  237. # pragma mark - External Methods
  238. - (void)setAnimationNamed:(nonnull NSString *)animationName {
  239. LOTComposition *comp = [LOTComposition animationNamed:animationName];
  240. [self _initializeAnimationContainer];
  241. [self _setupWithSceneModel:comp];
  242. }
  243. - (void)setAnimationNamed:(NSString *)animationName inBundle:(NSBundle *)bundle {
  244. LOTComposition *comp = [LOTComposition animationNamed:animationName inBundle:bundle];
  245. [self _initializeAnimationContainer];
  246. [self _setupWithSceneModel:comp];
  247. }
  248. - (void)setAnimationFromJSON:(nonnull NSDictionary *)animationJSON {
  249. LOTComposition *comp = [LOTComposition animationFromJSON:animationJSON];
  250. [self _initializeAnimationContainer];
  251. [self _setupWithSceneModel:comp];
  252. }
  253. - (void)setAnimationFromJSON:(NSDictionary *)animationJSON inBundle:(NSBundle *)bundle {
  254. LOTComposition *comp = [LOTComposition animationFromJSON:animationJSON inBundle:bundle];
  255. [self _initializeAnimationContainer];
  256. [self _setupWithSceneModel:comp];
  257. }
  258. # pragma mark - External Methods - Model
  259. - (void)setSceneModel:(LOTComposition *)sceneModel {
  260. [self _setupWithSceneModel:sceneModel];
  261. }
  262. # pragma mark - External Methods - Play Control
  263. - (void)play {
  264. if (!_sceneModel) {
  265. _isAnimationPlaying = YES;
  266. return;
  267. }
  268. [self playFromFrame:_sceneModel.startFrame toFrame:_sceneModel.endFrame withCompletion:nil];
  269. }
  270. - (void)playWithCompletion:(LOTAnimationCompletionBlock)completion {
  271. if (!_sceneModel) {
  272. _isAnimationPlaying = YES;
  273. self.completionBlock = completion;
  274. return;
  275. }
  276. [self playFromFrame:_sceneModel.startFrame toFrame:_sceneModel.endFrame withCompletion:completion];
  277. }
  278. - (void)playToProgress:(CGFloat)progress withCompletion:(nullable LOTAnimationCompletionBlock)completion {
  279. [self playFromProgress:0 toProgress:progress withCompletion:completion];
  280. }
  281. - (void)playFromProgress:(CGFloat)fromStartProgress
  282. toProgress:(CGFloat)toEndProgress
  283. withCompletion:(nullable LOTAnimationCompletionBlock)completion {
  284. if (!_sceneModel) {
  285. _isAnimationPlaying = YES;
  286. self.completionBlock = completion;
  287. _playRangeStartProgress = fromStartProgress;
  288. _playRangeEndProgress = toEndProgress;
  289. return;
  290. }
  291. [self playFromFrame:[self _frameForProgress:fromStartProgress]
  292. toFrame:[self _frameForProgress:toEndProgress]
  293. withCompletion:completion];
  294. }
  295. - (void)playToFrame:(nonnull NSNumber *)toFrame
  296. withCompletion:(nullable LOTAnimationCompletionBlock)completion {
  297. [self playFromFrame:_sceneModel.startFrame toFrame:toFrame withCompletion:completion];
  298. }
  299. - (void)playFromFrame:(nonnull NSNumber *)fromStartFrame
  300. toFrame:(nonnull NSNumber *)toEndFrame
  301. withCompletion:(nullable LOTAnimationCompletionBlock)completion {
  302. if (_isAnimationPlaying) {
  303. return;
  304. }
  305. _playRangeStartFrame = fromStartFrame;
  306. _playRangeEndFrame = toEndFrame;
  307. if (completion) {
  308. self.completionBlock = completion;
  309. }
  310. if (!_sceneModel) {
  311. _isAnimationPlaying = YES;
  312. return;
  313. }
  314. BOOL playingForward = ((_animationSpeed > 0) && (toEndFrame.floatValue > fromStartFrame.floatValue))
  315. || ((_animationSpeed < 0) && (fromStartFrame.floatValue > toEndFrame.floatValue));
  316. CGFloat leftFrameValue = MIN(fromStartFrame.floatValue, toEndFrame.floatValue);
  317. CGFloat rightFrameValue = MAX(fromStartFrame.floatValue, toEndFrame.floatValue);
  318. NSNumber *currentFrame = [self _frameForProgress:_animationProgress];
  319. currentFrame = @(MAX(MIN(currentFrame.floatValue, rightFrameValue), leftFrameValue));
  320. if (currentFrame.floatValue == rightFrameValue && playingForward) {
  321. currentFrame = @(leftFrameValue);
  322. } else if (currentFrame.floatValue == leftFrameValue && !playingForward) {
  323. currentFrame = @(rightFrameValue);
  324. }
  325. _animationProgress = [self _progressForFrame:currentFrame];
  326. CGFloat currentProgress = _animationProgress * (_sceneModel.endFrame.floatValue - _sceneModel.startFrame.floatValue);
  327. CGFloat skipProgress;
  328. if (playingForward) {
  329. skipProgress = currentProgress - leftFrameValue;
  330. } else {
  331. skipProgress = rightFrameValue - currentProgress;
  332. }
  333. NSTimeInterval offset = MAX(0, skipProgress) / _sceneModel.framerate.floatValue;
  334. if (!self.window) {
  335. _shouldRestoreStateWhenAttachedToWindow = YES;
  336. _completionBlockToRestoreWhenAttachedToWindow = self.completionBlock;
  337. self.completionBlock = nil;
  338. } else {
  339. NSTimeInterval duration = (ABS(toEndFrame.floatValue - fromStartFrame.floatValue) / _sceneModel.framerate.floatValue);
  340. CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"currentFrame"];
  341. animation.speed = _animationSpeed;
  342. animation.fromValue = fromStartFrame;
  343. animation.toValue = toEndFrame;
  344. animation.duration = duration;
  345. animation.fillMode = kCAFillModeBoth;
  346. animation.repeatCount = _loopAnimation ? HUGE_VALF : 1;
  347. animation.autoreverses = _autoReverseAnimation;
  348. animation.delegate = self;
  349. animation.removedOnCompletion = NO;
  350. if (offset != 0) {
  351. CFTimeInterval currentTime = CACurrentMediaTime();
  352. CFTimeInterval currentLayerTime = [self.layer convertTime:currentTime fromLayer:nil];
  353. animation.beginTime = currentLayerTime - (offset * 1 / _animationSpeed);
  354. }
  355. [_compContainer addAnimation:animation forKey:kCompContainerAnimationKey];
  356. _compContainer.shouldRasterize = NO;
  357. }
  358. _isAnimationPlaying = YES;
  359. }
  360. #pragma mark - Other Time Controls
  361. - (void)stop {
  362. _isAnimationPlaying = NO;
  363. if (_sceneModel) {
  364. [self setProgressWithFrame:_sceneModel.startFrame callCompletionIfNecessary:YES];
  365. }
  366. }
  367. - (void)pause {
  368. if (!_sceneModel ||
  369. !_isAnimationPlaying) {
  370. _isAnimationPlaying = NO;
  371. return;
  372. }
  373. NSNumber *frame = [_compContainer.presentationLayer.currentFrame copy];
  374. [self setProgressWithFrame:frame callCompletionIfNecessary:YES];
  375. }
  376. - (void)setAnimationProgress:(CGFloat)animationProgress {
  377. if (!_sceneModel) {
  378. _animationProgress = animationProgress;
  379. return;
  380. }
  381. [self setProgressWithFrame:[self _frameForProgress:animationProgress] callCompletionIfNecessary:YES];
  382. }
  383. - (void)setProgressWithFrame:(nonnull NSNumber *)currentFrame {
  384. [self setProgressWithFrame:currentFrame callCompletionIfNecessary:YES];
  385. }
  386. - (void)setProgressWithFrame:(nonnull NSNumber *)currentFrame callCompletionIfNecessary:(BOOL)callCompletion {
  387. [self _removeCurrentAnimationIfNecessary];
  388. if (_shouldRestoreStateWhenAttachedToWindow) {
  389. _shouldRestoreStateWhenAttachedToWindow = NO;
  390. self.completionBlock = _completionBlockToRestoreWhenAttachedToWindow;
  391. _completionBlockToRestoreWhenAttachedToWindow = nil;
  392. }
  393. _animationProgress = [self _progressForFrame:currentFrame];
  394. [CATransaction begin];
  395. [CATransaction setDisableActions:YES];
  396. _compContainer.currentFrame = currentFrame;
  397. [_compContainer setNeedsDisplay];
  398. [CATransaction commit];
  399. if (callCompletion) {
  400. [self _callCompletionIfNecessary:NO];
  401. }
  402. }
  403. - (void)setLoopAnimation:(BOOL)loopAnimation {
  404. _loopAnimation = loopAnimation;
  405. if (_isAnimationPlaying && _sceneModel) {
  406. NSNumber *frame = [_compContainer.presentationLayer.currentFrame copy];
  407. [self setProgressWithFrame:frame callCompletionIfNecessary:NO];
  408. [self playFromFrame:_playRangeStartFrame toFrame:_playRangeEndFrame withCompletion:self.completionBlock];
  409. }
  410. }
  411. - (void)setAnimationSpeed:(CGFloat)animationSpeed {
  412. _animationSpeed = animationSpeed;
  413. if (_isAnimationPlaying && _sceneModel) {
  414. NSNumber *frame = [_compContainer.presentationLayer.currentFrame copy];
  415. [self setProgressWithFrame:frame callCompletionIfNecessary:NO];
  416. [self playFromFrame:_playRangeStartFrame toFrame:_playRangeEndFrame withCompletion:self.completionBlock];
  417. }
  418. }
  419. - (void)forceDrawingUpdate {
  420. [self _layoutAndForceUpdate];
  421. }
  422. # pragma mark - External Methods - Idle Rasterization
  423. - (void)setShouldRasterizeWhenIdle:(BOOL)shouldRasterize {
  424. _shouldRasterizeWhenIdle = shouldRasterize;
  425. if (!_isAnimationPlaying) {
  426. _compContainer.shouldRasterize = _shouldRasterizeWhenIdle;
  427. }
  428. }
  429. # pragma mark - External Methods - Cache
  430. - (void)setCacheEnable:(BOOL)cacheEnable {
  431. _cacheEnable = cacheEnable;
  432. if (!self.sceneModel.cacheKey) {
  433. return;
  434. }
  435. if (cacheEnable) {
  436. [[LOTAnimationCache sharedCache] addAnimation:_sceneModel forKey:self.sceneModel.cacheKey];
  437. } else {
  438. [[LOTAnimationCache sharedCache] removeAnimationForKey:self.sceneModel.cacheKey];
  439. }
  440. }
  441. # pragma mark - External Methods - Interactive Controls
  442. - (void)setValueDelegate:(id<LOTValueDelegate> _Nonnull)delegate
  443. forKeypath:(LOTKeypath * _Nonnull)keypath {
  444. [_compContainer setValueDelegate:delegate forKeypath:keypath];
  445. [self _layoutAndForceUpdate];
  446. }
  447. - (nullable NSArray *)keysForKeyPath:(nonnull LOTKeypath *)keypath {
  448. return [_compContainer keysForKeyPath:keypath];
  449. }
  450. - (CGPoint)convertPoint:(CGPoint)point
  451. toKeypathLayer:(nonnull LOTKeypath *)keypath {
  452. [self _layoutAndForceUpdate];
  453. return [_compContainer convertPoint:point toKeypathLayer:keypath withParentLayer:self.layer];
  454. }
  455. - (CGRect)convertRect:(CGRect)rect
  456. toKeypathLayer:(nonnull LOTKeypath *)keypath {
  457. [self _layoutAndForceUpdate];
  458. return [_compContainer convertRect:rect toKeypathLayer:keypath withParentLayer:self.layer];
  459. }
  460. - (CGPoint)convertPoint:(CGPoint)point
  461. fromKeypathLayer:(nonnull LOTKeypath *)keypath {
  462. [self _layoutAndForceUpdate];
  463. return [_compContainer convertPoint:point fromKeypathLayer:keypath withParentLayer:self.layer];
  464. }
  465. - (CGRect)convertRect:(CGRect)rect
  466. fromKeypathLayer:(nonnull LOTKeypath *)keypath {
  467. [self _layoutAndForceUpdate];
  468. return [_compContainer convertRect:rect fromKeypathLayer:keypath withParentLayer:self.layer];
  469. }
  470. #if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
  471. - (void)addSubview:(nonnull LOTView *)view
  472. toKeypathLayer:(nonnull LOTKeypath *)keypath {
  473. [self _layoutAndForceUpdate];
  474. CGRect viewRect = view.frame;
  475. LOTView *wrapperView = [[LOTView alloc] initWithFrame:viewRect];
  476. view.frame = view.bounds;
  477. view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  478. [wrapperView addSubview:view];
  479. [self addSubview:wrapperView];
  480. [_compContainer addSublayer:wrapperView.layer toKeypathLayer:keypath];
  481. }
  482. - (void)maskSubview:(nonnull LOTView *)view
  483. toKeypathLayer:(nonnull LOTKeypath *)keypath {
  484. [self _layoutAndForceUpdate];
  485. CGRect viewRect = view.frame;
  486. LOTView *wrapperView = [[LOTView alloc] initWithFrame:viewRect];
  487. view.frame = view.bounds;
  488. view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  489. [wrapperView addSubview:view];
  490. [self addSubview:wrapperView];
  491. [_compContainer maskSublayer:wrapperView.layer toKeypathLayer:keypath];
  492. }
  493. #else
  494. - (void)addSubview:(nonnull LOTView *)view
  495. toKeypathLayer:(nonnull LOTKeypath *)keypath {
  496. [self _layout];
  497. CGRect viewRect = view.frame;
  498. LOTView *wrapperView = [[LOTView alloc] initWithFrame:viewRect];
  499. view.frame = view.bounds;
  500. view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  501. [wrapperView addSubview:view];
  502. [self addSubview:wrapperView];
  503. [_compContainer addSublayer:wrapperView.layer toKeypathLayer:keypath];
  504. }
  505. - (void)maskSubview:(nonnull LOTView *)view
  506. toKeypathLayer:(nonnull LOTKeypath *)keypath {
  507. [self _layout];
  508. CGRect viewRect = view.frame;
  509. LOTView *wrapperView = [[LOTView alloc] initWithFrame:viewRect];
  510. view.frame = view.bounds;
  511. view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  512. [wrapperView addSubview:view];
  513. [self addSubview:wrapperView];
  514. [_compContainer maskSublayer:wrapperView.layer toKeypathLayer:keypath];
  515. }
  516. #endif
  517. # pragma mark - Semi-Private Methods
  518. - (CALayer * _Nullable)layerForKey:(NSString * _Nonnull)keyname {
  519. return _compContainer.childMap[keyname];
  520. }
  521. - (NSArray * _Nonnull)compositionLayers {
  522. return _compContainer.childLayers;
  523. }
  524. # pragma mark - Getters and Setters
  525. - (CGFloat)animationDuration {
  526. if (!_sceneModel) {
  527. return 0;
  528. }
  529. CAAnimation *play = [_compContainer animationForKey:kCompContainerAnimationKey];
  530. if (play) {
  531. return play.duration;
  532. }
  533. return (_sceneModel.endFrame.floatValue - _sceneModel.startFrame.floatValue) / _sceneModel.framerate.floatValue;
  534. }
  535. - (CGFloat)animationProgress {
  536. if (_isAnimationPlaying &&
  537. _compContainer.presentationLayer) {
  538. CGFloat activeProgress = [self _progressForFrame:[(LOTCompositionContainer *)_compContainer.presentationLayer currentFrame]];
  539. return activeProgress;
  540. }
  541. return _animationProgress;
  542. }
  543. # pragma mark - Overrides
  544. #if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
  545. #define LOTViewContentMode UIViewContentMode
  546. #define LOTViewContentModeScaleToFill UIViewContentModeScaleToFill
  547. #define LOTViewContentModeScaleAspectFit UIViewContentModeScaleAspectFit
  548. #define LOTViewContentModeScaleAspectFill UIViewContentModeScaleAspectFill
  549. #define LOTViewContentModeRedraw UIViewContentModeRedraw
  550. #define LOTViewContentModeCenter UIViewContentModeCenter
  551. #define LOTViewContentModeTop UIViewContentModeTop
  552. #define LOTViewContentModeBottom UIViewContentModeBottom
  553. #define LOTViewContentModeLeft UIViewContentModeLeft
  554. #define LOTViewContentModeRight UIViewContentModeRight
  555. #define LOTViewContentModeTopLeft UIViewContentModeTopLeft
  556. #define LOTViewContentModeTopRight UIViewContentModeTopRight
  557. #define LOTViewContentModeBottomLeft UIViewContentModeBottomLeft
  558. #define LOTViewContentModeBottomRight UIViewContentModeBottomRight
  559. - (CGSize)intrinsicContentSize {
  560. if (!_sceneModel) {
  561. return CGSizeMake(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric);
  562. }
  563. return _sceneModel.compBounds.size;
  564. }
  565. - (void)didMoveToSuperview {
  566. [super didMoveToSuperview];
  567. if (self.superview == nil) {
  568. [self _callCompletionIfNecessary:NO];
  569. }
  570. }
  571. - (void)willMoveToWindow:(UIWindow *)newWindow {
  572. [self _handleWindowChanges:(newWindow != nil)];
  573. }
  574. - (void)didMoveToWindow {
  575. _compContainer.rasterizationScale = self.window.screen.scale;
  576. }
  577. - (void)setContentMode:(LOTViewContentMode)contentMode {
  578. [super setContentMode:contentMode];
  579. [self setNeedsLayout];
  580. }
  581. - (void)layoutSubviews {
  582. [super layoutSubviews];
  583. [self _layout];
  584. }
  585. #else
  586. - (void)viewWillMoveToWindow:(NSWindow *)newWindow {
  587. [self _handleWindowChanges:(newWindow != nil)];
  588. }
  589. - (void)viewDidMoveToWindow {
  590. _compContainer.rasterizationScale = self.window.screen.backingScaleFactor;
  591. }
  592. - (void)setCompletionBlock:(LOTAnimationCompletionBlock)completionBlock {
  593. if (completionBlock) {
  594. _completionBlock = ^(BOOL finished) {
  595. dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(finished); });
  596. };
  597. }
  598. else {
  599. _completionBlock = nil;
  600. }
  601. }
  602. - (void)setContentMode:(LOTViewContentMode)contentMode {
  603. _contentMode = contentMode;
  604. [self setNeedsLayout];
  605. }
  606. - (void)setNeedsLayout {
  607. self.needsLayout = YES;
  608. }
  609. - (BOOL)isFlipped {
  610. return YES;
  611. }
  612. - (BOOL)wantsUpdateLayer {
  613. return YES;
  614. }
  615. - (void)layout {
  616. [super layout];
  617. [self _layout];
  618. }
  619. #endif
  620. - (void)_layoutAndForceUpdate {
  621. [CATransaction begin];
  622. [CATransaction setDisableActions:YES];
  623. [self _layout];
  624. [_compContainer displayWithFrame:_compContainer.currentFrame forceUpdate:YES];
  625. [CATransaction commit];
  626. }
  627. - (void)_layout {
  628. CGPoint centerPoint = LOT_RectGetCenterPoint(self.bounds);
  629. CATransform3D xform;
  630. if (self.contentMode == LOTViewContentModeScaleToFill) {
  631. CGSize scaleSize = CGSizeMake(self.bounds.size.width / self.sceneModel.compBounds.size.width,
  632. self.bounds.size.height / self.sceneModel.compBounds.size.height);
  633. xform = CATransform3DMakeScale(scaleSize.width, scaleSize.height, 1);
  634. } else if (self.contentMode == LOTViewContentModeScaleAspectFit) {
  635. CGFloat compAspect = self.sceneModel.compBounds.size.width / self.sceneModel.compBounds.size.height;
  636. CGFloat viewAspect = self.bounds.size.width / self.bounds.size.height;
  637. BOOL scaleWidth = compAspect > viewAspect;
  638. CGFloat dominantDimension = scaleWidth ? self.bounds.size.width : self.bounds.size.height;
  639. CGFloat compDimension = scaleWidth ? self.sceneModel.compBounds.size.width : self.sceneModel.compBounds.size.height;
  640. CGFloat scale = dominantDimension / compDimension;
  641. xform = CATransform3DMakeScale(scale, scale, 1);
  642. } else if (self.contentMode == LOTViewContentModeScaleAspectFill) {
  643. CGFloat compAspect = self.sceneModel.compBounds.size.width / self.sceneModel.compBounds.size.height;
  644. CGFloat viewAspect = self.bounds.size.width / self.bounds.size.height;
  645. BOOL scaleWidth = compAspect < viewAspect;
  646. CGFloat dominantDimension = scaleWidth ? self.bounds.size.width : self.bounds.size.height;
  647. CGFloat compDimension = scaleWidth ? self.sceneModel.compBounds.size.width : self.sceneModel.compBounds.size.height;
  648. CGFloat scale = dominantDimension / compDimension;
  649. xform = CATransform3DMakeScale(scale, scale, 1);
  650. } else {
  651. xform = CATransform3DIdentity;
  652. }
  653. [CATransaction begin];
  654. [CATransaction setDisableActions:YES];
  655. _compContainer.transform = CATransform3DIdentity;
  656. _compContainer.bounds = _sceneModel.compBounds;
  657. _compContainer.viewportBounds = _sceneModel.compBounds;
  658. _compContainer.transform = xform;
  659. _compContainer.position = centerPoint;
  660. [CATransaction commit];
  661. }
  662. # pragma mark - CAAnimationDelegate
  663. - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)complete {
  664. if ([_compContainer animationForKey:kCompContainerAnimationKey] == anim &&
  665. [anim isKindOfClass:[CABasicAnimation class]]) {
  666. CABasicAnimation *playAnimation = (CABasicAnimation *)anim;
  667. NSNumber *frame = _compContainer.presentationLayer.currentFrame;
  668. if (complete) {
  669. // Set the final frame based on the animation to/from values. If playing forward, use the
  670. // toValue otherwise we want to end on the fromValue.
  671. frame = [self _isSpeedNegative] ? (NSNumber *)playAnimation.toValue : (NSNumber *)playAnimation.fromValue;
  672. }
  673. [self _removeCurrentAnimationIfNecessary];
  674. [self setProgressWithFrame:frame callCompletionIfNecessary:NO];
  675. [self _callCompletionIfNecessary:complete];
  676. }
  677. }
  678. # pragma mark - DEPRECATED
  679. - (void)addSubview:(nonnull LOTView *)view
  680. toLayerNamed:(nonnull NSString *)layer
  681. applyTransform:(BOOL)applyTransform {
  682. NSLog(@"%s: Function is DEPRECATED. Please use addSubview:forKeypathLayer:", __PRETTY_FUNCTION__);
  683. LOTKeypath *keypath = [LOTKeypath keypathWithString:layer];
  684. if (applyTransform) {
  685. [self addSubview:view toKeypathLayer:keypath];
  686. } else {
  687. [self maskSubview:view toKeypathLayer:keypath];
  688. }
  689. }
  690. - (CGRect)convertRect:(CGRect)rect
  691. toLayerNamed:(NSString *_Nullable)layerName {
  692. NSLog(@"%s: Function is DEPRECATED. Please use convertRect:forKeypathLayer:", __PRETTY_FUNCTION__);
  693. LOTKeypath *keypath = [LOTKeypath keypathWithString:layerName];
  694. return [self convertRect:rect toKeypathLayer:keypath];
  695. }
  696. - (void)setValue:(nonnull id)value
  697. forKeypath:(nonnull NSString *)keypath
  698. atFrame:(nullable NSNumber *)frame {
  699. NSLog(@"%s: Function is DEPRECATED and no longer functional. Please use setValueCallback:forKeypath:", __PRETTY_FUNCTION__);
  700. }
  701. - (void)logHierarchyKeypaths {
  702. NSArray *keypaths = [self keysForKeyPath:[LOTKeypath keypathWithString:@"**"]];
  703. for (NSString *keypath in keypaths) {
  704. NSLog(@"%@", keypath);
  705. }
  706. }
  707. @end