UNPKG

22.6 kBMarkdownView Raw
1# Lottie for iOS, MacOS (and [Android](https://github.com/airbnb/lottie-android) and [React Native](https://github.com/airbnb/lottie-react-native))
2
3### Table of Contents
4- [Introduction](#introduction)
5- [Installing Lottie](#installing-lottie)
6- [iOS Sample App](#ios-sample-app)
7- [MacOS Sample App](#macos-sample-app)
8- [Objective C Examples](#objective-c-examples)
9- [Swift Examples](#swift-examples)
10- [Debugging Lottie](#debugging)
11- [iOS View Controller Transitioning](#ios-view-controller-transitioning)
12- [Changing Animations At Runtime](#changing-animations-at-runtime)
13- [Animated Controls and Switches](#animated-controls-and-switches)
14- [Adding Subviews to Animation](#adding-views-to-an-animation-at-runtime)
15- [Supported After Effects Features](#supported-after-effects-features)
16- [Currently Unsupported After Effects Features](#currently-unsupported-after-effects-features)
17- [Community Contributions](#community-contributions)
18- [Alternatives](#alternatives)
19- [Why is it called Lottie?](#why-is-it-called-lottie)
20- [Contributing](#contributing)
21- [Issues or feature requests?](#issues-or-feature-requests)
22
23
24## Introduction
25
26Lottie is a mobile library for Android and iOS that parses [Adobe After Effects](http://www.adobe.com/products/aftereffects.html) animations exported as json with [bodymovin](https://github.com/bodymovin/bodymovin) and renders the vector animations natively on mobile and through React Native!
27
28For the first time, designers can create **and ship** beautiful animations without an engineer painstakingly recreating it by hand.
29Since the animation is backed by JSON they are extremely small in size but can be large in complexity!
30Animations can be played, resized, looped, sped up, slowed down, reversed, and even interactively scrubbed.
31Lottie can play or loop just a portion of the animation as well, the possibilities are endless!
32Animations can even be ***changed at runtime*** in various ways! Change the color, position or any keyframable value!
33Lottie also supports native UIViewController Transitions out of the box!
34
35Here is just a small sampling of the power of Lottie
36
37![Example1](_Gifs/Examples1.gif)
38![Example2](_Gifs/Examples2.gif)
39
40<img src="_Gifs/Community 2_3.gif" />
41
42![Example3](_Gifs/Examples3.gif)
43
44![Abcs](_Gifs/Examples4.gif)
45
46## Installing Lottie
47
48### Github Repo
49You can pull the [Lottie Github Repo](https://github.com/airbnb/lottie-ios/) and include the Lottie.xcodeproj to build a dynamic or static library.
50
51### Cocoapods
52Get [Cocoapods](https://cocoapods.org/)
53Add the pod to your podfile
54```
55pod 'lottie-ios'
56```
57run
58```
59pod install
60```
61
62After installing the cocoapod into your project import Lottie with
63Objective C
64`#import <Lottie/Lottie.h>`
65Swift
66`import Lottie`
67
68### Carthage
69Get [Carthage](https://github.com/Carthage/Carthage)
70
71Add Lottie to your Cartfile
72```
73github "airbnb/lottie-ios" "master"
74```
75run
76```
77carthage update
78```
79
80In your application targets “General” tab under the “Linked Frameworks and Libraries” section, drag and drop lottie-ios.framework from the Carthage/Build/iOS directory that `carthage update` produced.
81
82## iOS Sample App
83
84Clone this repo and try out [the Sample App](https://github.com/airbnb/lottie-ios/tree/master/Example)
85The repo can build a MacOS Example and an iOS Example
86
87The iOS Example App demos several of the features of Lottie
88
89![Example 1](_Gifs/iosexample1.png)![Example 2](_Gifs/iosexample2.png)
90![Example 3](_Gifs/iosexample3.png)
91
92The animation Explorer allows you to scrub, play, loop, and resize animations.
93Animations can be loaded from the app bundle or from [Lottie Files](http://www.lottiefiles.com) using the built in QR Code reader.
94
95## MacOS Sample App
96
97Clone this repo and try out [the Sample App](https://github.com/airbnb/lottie-ios/tree/master/Example)
98The repo can build a MacOS Example and an iOS Example
99
100![Lottie Viewer](_Gifs/macexample.png)
101
102The Lottie Viewer for MacOS allows you to drag and drop JSON files to open, play, scrub and loop animations. This app is backed by the same animation code as the iOS app, so you will get an accurate representation of Mac and iOS animations.
103
104
105## Objective C Examples
106
107
108Lottie animations can be loaded from bundled JSON or from a URL
109To bundle JSON just add it and any images that the animation requires to your target in xcode.
110
111```objective-c
112LOTAnimationView *animation = [LOTAnimationView animationNamed:@"Lottie"];
113[self.view addSubview:animation];
114[animation playWithCompletion:^(BOOL animationFinished) {
115 // Do Something
116}];
117```
118
119If you are working with multiple bundles you can use.
120
121```objective-c
122LOTAnimationView *animation = [LOTAnimationView animationNamed:@"Lottie" inBundle:[NSBundle YOUR_BUNDLE]];
123[self.view addSubview:animation];
124[animation playWithCompletion:^(BOOL animationFinished) {
125 // Do Something
126}];
127```
128
129Or you can load it programmatically from a NSURL
130```objective-c
131LOTAnimationView *animation = [[LOTAnimationView alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
132[self.view addSubview:animation];
133```
134
135Lottie supports the iOS `UIViewContentModes` aspectFit, aspectFill and scaleFill
136
137You can also set the animation progress interactively.
138```objective-c
139CGPoint translation = [gesture getTranslationInView:self.view];
140CGFloat progress = translation.y / self.view.bounds.size.height;
141animationView.animationProgress = progress;
142```
143
144Or you can play just a portion of the animation:
145```objective-c
146[lottieAnimation playFromProgress:0.25 toProgress:0.5 withCompletion:^(BOOL animationFinished) {
147 // Do Something
148}];
149```
150## Swift Examples
151
152Lottie animations can be loaded from bundled JSON or from a URL
153To bundle JSON just add it and any images that the animation requires to your target in xcode.
154
155```swift
156let animationView = LOTAnimationView(name: "LottieLogo")
157self.view.addSubview(animationView)
158animationView.play{ (finished) in
159 // Do Something
160}
161```
162
163If your animation is in another bundle you can use
164```swift
165let animationView = LOTAnimationView(name: "LottieLogo" bundle:yourBundle)
166self.view.addSubview(animationView)
167animationView.play()
168```
169
170Or you can load it asynchronously from a URL
171```swift
172let animationView = LOTAnimationView(contentsOf: WebURL)
173self.view.addSubview(animationView)
174animationView.play()
175```
176
177You can also set the animation progress interactively.
178```swift
179let translation = gesture.getTranslationInView(self.view)
180let progress = translation.y / self.view.bounds.size.height;
181animationView.animationProgress = progress
182```
183
184Or you can play just a portion of the animation:
185```swift
186animationView.play(fromProgress: 0.25, toProgress: 0.5, withCompletion: nil)
187```
188
189## iOS View Controller Transitioning
190
191Lottie comes with a `UIViewController` animation-controller for making custom viewController transitions!
192
193![Transition1](_Gifs/transitionMasked.gif)
194![Transition2](_Gifs/transitionPosition.gif)
195
196Just become the delegate for a transition
197
198```objective-c
199- (void)_showTransitionA {
200 ToAnimationViewController *vc = [[ToAnimationViewController alloc] init];
201 vc.transitioningDelegate = self;
202 [self presentViewController:vc animated:YES completion:NULL];
203}
204```
205
206And implement the delegate methods with a `LOTAnimationTransitionController`
207
208```objective-c
209#pragma mark -- View Controller Transitioning
210
211- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
212 LOTAnimationTransitionController *animationController = [[LOTAnimationTransitionController alloc] initWithAnimationNamed:@"vcTransition1" fromLayerNamed:@"outLayer" toLayerNamed:@"inLayer" applyAnimationTransform:NO];
213 return animationController;
214}
215
216- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
217 LOTAnimationTransitionController *animationController = [[LOTAnimationTransitionController alloc] initWithAnimationNamed:@"vcTransition2" fromLayerNamed:@"outLayer" toLayerNamed:@"inLayer" applyAnimationTransform:NO];
218 return animationController;
219}
220
221```
222
223By setting `applyAnimationTransform` to YES you can make the Lottie animation move the from and to view controllers. They will be positioned at the origin of the layer. When set to NO Lottie just masks the view controller with the specified layer while resepecting z order.
224
225## Debugging
226Lottie has a couple of debugging features to know about.
227When an animation is loaded unsupported features are logged out in the console with their function names.
228
229If you checkout LOTHelpers.h you will see two debug flags. `ENABLE_DEBUG_LOGGING` and `ENABLE_DEBUG_SHAPES`.
230`ENABLE_DEBUG_LOGGING` increases the verbosity of Lottie Logging. It logs anytime an animation node is set during animation. If your animation if not working, turn this on and play your animation. The console log might give you some clues as to whats going on.
231
232`ENABLE_DEBUG_SHAPES` Draws a colored square for the anchor-point of every layer and shape. This is helpful to see if anything is on screen.
233
234### Keypaths
235
236LOTAnimationView provides `- (void)logHierarchyKeypaths` which will recursively log all settable keypaths for the animation. This is helpful for changing animationations at runtime.
237
238## Adding Views to an Animation at Runtime
239
240Not only can you [change animations at runtime](#changing-animations-at-runtime) with Lottie, you can also add custom UI to a LOTAnimation at runtime.
241The example below shows some advance uses of this to create a dynamic image loader.
242
243## A Dynamic Image Loading Spinner
244
245![Spinner](/_Gifs/spinner.gif)
246
247The example above shows a single LOTAnimationView that is set with a loading spinner animation. The loading spinner loops a portion of its animation while an image is downloaded asynchronously. When the download is complete, the image is added to the animation and the rest of the animation is played seamlessly. The image is cleanly animated in and a completion block is called.
248
249![Spinner_Alt](/_Gifs/spinner_Alternative.gif)
250
251Now, the animation has been changed by a designer and needs to be updated. All that is required is updating the JSON file in the bundle. No code change needed!
252
253![Spinner_Dark](/_Gifs/spinner_DarkMode.gif)
254
255Here, the design has decided to add a 'Dark Mode' to the app. Just a few lines of code change the color of the animation at runtime.
256
257
258Pretty powerful eh?
259
260Check out the code below for an example!
261
262```swift
263
264import UIKit
265import Lottie
266
267class ViewController: UIViewController {
268
269 var animationView: LOTAnimationView = LOTAnimationView(name: "SpinnerSpin");
270
271 override func viewDidLoad() {
272 super.viewDidLoad()
273
274 // Setup our animaiton view
275 animationView.contentMode = .scaleAspectFill
276 animationView.frame = CGRect(x: 20, y: 20, width: 200, height: 200)
277
278 self.view.addSubview(animationView)
279 // Lets change some of the properties of the animation
280 // We arent going to use the MaskLayer, so lets just hide it
281 animationView.setValue(0, forKeypath: "MaskLayer.Ellipse 1.Transform.Opacity", atFrame: 0)
282 // All of the strokes and fills are white, lets make them DarkGrey
283 animationView.setValue(UIColor.darkGray, forKeypath: "OuterRing.Stroke.Color", atFrame: 0)
284 animationView.setValue(UIColor.darkGray, forKeypath: "InnerRing.Stroke.Color", atFrame: 0)
285 animationView.setValue(UIColor.darkGray, forKeypath: "InnerRing.Fill.Color", atFrame: 0)
286
287 // Lets turn looping on, since we want it to repeat while the image is 'Downloading'
288 animationView.loopAnimation = true
289 // Now play from 0 to 0.5 progress and loop indefinitely.
290 animationView.play(fromProgress: 0, toProgress: 0.5, withCompletion: nil)
291
292 // Lets simulate a download that finishes in 4 seconds.
293 let dispatchTime = DispatchTime.now() + 4.0
294 DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
295 self.simulateImageDownloaded()
296 }
297 }
298
299 func simulateImageDownloaded() {
300 // Our downloaded image
301 let image = UIImage(named: "avatar.jpg")
302 let imageView = UIImageView(image: image)
303
304 // We want the image to show up centered in the animation view at 150Px150P
305 // Convert that rect to the animations coordinate space
306 // The origin is set to -75, -75 because the origin is centered in the animation view
307 let imageRect = animationView.convert(CGRect(x: -75, y: -75, width: 150, height: 150), toLayerNamed: nil)
308
309 // Setup our image view with the rect and add rounded corners
310 imageView.frame = imageRect
311 imageView.layer.masksToBounds = true
312 imageView.layer.cornerRadius = imageRect.width / 2;
313
314 // Now we set the completion block on the currently running animation
315 animationView.completionBlock = { (result: Bool) in ()
316 // Add the image view to the layer named "TransformLayer"
317 self.animationView.addSubview(imageView, toLayerNamed: "TransformLayer", applyTransform: true)
318 // Now play the last half of the animation
319 self.animationView.play(fromProgress: 0.5, toProgress: 1, withCompletion: { (complete: Bool) in
320 // Now the animation has finished and our image is displayed on screen
321 print("Image Downloaded and Displayed")
322 })
323 }
324
325 // Turn looping off. Once the current loop finishes the animation will stop
326 // and the completion block will be called.
327 animationView.loopAnimation = false
328 }
329
330}
331
332```
333
334## Changing Animations At Runtime
335
336Lottie can do more than just play beautiful animations. Lottie allows you to **change** animations at runtime.
337
338### Say we want to create 4 toggle switches.
339![Toggle](_Gifs/switch_Normal.gif)
340Its easy to create the four switches and play them:
341
342```swift
343let animationView = LOTAnimationView(name: "toggle");
344self.view.addSubview(animationView)
345animationView.frame.origin.x = 40
346animationView.frame.origin.y = 20
347animationView.autoReverseAnimation = true
348animationView.loopAnimation = true
349animationView.play()
350
351let animationView2 = LOTAnimationView(name: "toggle");
352self.view.addSubview(animationView2)
353animationView2.frame.origin.x = 40
354animationView2.frame.origin.y = animationView.frame.maxY + 4
355animationView2.autoReverseAnimation = true
356animationView2.loopAnimation = true
357animationView2.play()
358
359let animationView3 = LOTAnimationView(name: "toggle");
360self.view.addSubview(animationView3)
361animationView3.frame.origin.x = 40
362animationView3.frame.origin.y = animationView2.frame.maxY + 4
363animationView3.autoReverseAnimation = true
364animationView3.loopAnimation = true
365animationView3.play()
366
367let animationView4 = LOTAnimationView(name: "toggle");
368self.view.addSubview(animationView4)
369animationView4.frame.origin.x = 40
370animationView4.frame.origin.y = animationView3.frame.maxY + 4
371animationView4.autoReverseAnimation = true
372animationView4.loopAnimation = true
373animationView4.play()
374
375```
376### Now lets change their colors
377![Recolored Toggle](_Gifs/switch_BgColors.gif)
378```swift
379animationView2.setValue(UIColor.green, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
380animationView3.setValue(UIColor.red, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
381animationView4.setValue(UIColor.orange, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
382```
383
384```objective-c
385[animationView2 setValue:[UIColor greenColor] forKeypath:@"BG-On.Group 1.Fill 1.Color" atFrame:@0];
386```
387The keyPath is a dot separated path of layer and property names from After Effects.
388LOTAnimationView provides `- (void)logHierarchyKeypaths` which will recursively log all settable keypaths for the animation.
389![Key Path](_Gifs/aftereffectskeypath.png)
390"BG-On.Group 1.Fill 1.Color"
391
392### Now lets change a couple of properties
393![Multiple Colors](_Gifs/switch_MultipleBgs.gif)
394```swift
395animationView2.setValue(UIColor.green, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
396animationView2.setValue(UIColor.red, forKeypath: "BG-Off.Group 1.Fill 1.Color", atFrame: 0)
397```
398
399Lottie allows you to change **any** property that is animatable in After Effects. If a keyframe does not exist, a linear keyframe is created for you. If a keyframe does exist then just its data is replaced.
400
401## Animated Controls and Switches
402
403![Animated Buttons](_Gifs/switchTest.gif)
404
405Lottie also has a custom subclass of UIControl for creating custom animatable interactive controls.
406Currently Lottie has `LOTAnimatedSwitch` which is a toggle style switch control. Tapping on the switch plays either the On-Off or Off-On animation and sends out a UIControlStateValueChanged broadcast to all targets. It is used in the same way UISwitch is used with a few additions to setup the animation with Lottie.
407
408You initialize the switch either using the conveneince method or by supplying the animation directly.
409
410```
411// Convenience
412LOTAnimatedSwitch *toggle1 = [LOTAnimatedSwitch switchNamed:@"Switch"];
413
414// Manually
415LOTComposition *comp = [LOTComposition animationNamed:@"Switch"];
416LOTAnimatedSwitch *toggle1 = [[LOTAnimatedSwitch alloc] initWithFrame:CGRectZero];
417[toggle1 setAnimationComp:comp];
418```
419
420You can also specify a specific portion of the animation's timeline for the On and Off animation.
421By default `LOTAnimatedSwitch` will play the animation forward for On and backwards for off.
422
423Lets say that the supplied animation animates ON from 0.5-1 progress and OFF from 0-0.5:
424
425```
426/// On animation is 0.5 to 1 progress.
427[toggle1 setProgressRangeForOnState:0.5 toProgress:1];
428
429/// Off animation is 0 to 0.5 progress.
430[toggle1 setProgressRangeForOffState:0 toProgress:0.5];
431```
432
433Also, all LOTAnimatedControls add support for changing appearance for state changes. This requires some setup in After Effects. Lottie will switch visible animated layers based on the controls state. This can be used to have Disabled, selected, or Highlighted states. These states are associated with layer names in After Effects, and are dynamically displayed as the control changes states.
434
435Lets say we have a toggle switch with a Normal and Disabled state. In Effects we have a composition that contains Precomps of the regular "Button" and disabled "Disabled" states. They have different visual styles.
436
437![Regular](_Gifs/switch_enabled.png)
438![Disabled](_Gifs/switch_disabled.png)
439
440Now in code we can associate `UIControlState` with these layers
441
442```
443// Specify the layer names for different states
444[statefulSwitch setLayerName:@"Button" forState:UIControlStateNormal];
445[statefulSwitch setLayerName:@"Disabled" forState:UIControlStateDisabled];
446
447// Changes visual appearance by switching animation layer to "Disabled"
448statefulSwitch.enabled = NO;
449
450// Changes visual appearance by switching animation layer to "Button"
451statefulSwitch.enabled = YES;
452```
453
454## Supported After Effects Features
455
456### Keyframe Interpolation
457
458---
459
460* Linear Interpolation
461* Bezier Interpolation
462* Hold Interpolation
463* Rove Across Time
464* Spatial Bezier
465
466### Solids
467
468---
469
470* Transform Anchor Point
471* Transform Position
472* Transform Scale
473* Transform Rotation
474* Transform Opacity
475
476### Masks
477
478---
479
480* Path
481* Opacity
482* Multiple Masks (additive, subtractive and intersection)
483
484### Track Mattes
485
486---
487
488* Alpha Matte
489
490### Parenting
491
492---
493
494* Multiple Parenting
495* Nulls
496
497### Shape Layers
498
499---
500
501* Anchor Point
502* Position
503* Scale
504* Rotation
505* Opacity
506* Path
507* Group Transforms (Anchor point, position, scale etc)
508* Rectangle (All properties)
509* Eclipse (All properties)
510* Multiple paths in one group
511* Even-Odd winding paths
512* Reverse Fill Rule
513
514#### Stroke (shape layer)
515
516---
517
518* Stroke Color
519* Stroke Opacity
520* Stroke Width
521* Line Cap
522* Dashes (Now Animated!)
523
524#### Fill (shape layer)
525
526---
527
528* Fill Color
529* Fill Opacity
530
531#### Trim Paths (shape layer)
532
533---
534
535* Trim Paths Start
536* Trim Paths End
537* Trim Paths Offset
538
539### Repeaters
540
541---
542
543* Supports repeater transforms
544* Offset currently not supported.
545
546### Gradients
547
548---
549
550* Support for Linear Gradients
551* Support for Radial Gradients
552
553### Polystar and Polygon
554
555---
556
557* Supported! Theres a known bug if the roundness is greater than 100 percent.
558
559#### Layer Features
560
561---
562
563* Precomps
564* Image Layers
565* Shape Layers
566* Null Layers
567* Solid Layers
568* Parenting Layers
569* Alpha Matte Layers
570
571## Currently Unsupported After Effects Features
572
573* Merge Shapes
574* Alpha Inverted Masks
575* Trim Shapes Individually feature of Trim Paths
576* Expressions
577* 3d Layer support
578* Time remapping / Layer Reverse
579* Layer Blend Modes
580* Layer Effects
581
582
583## Community Contributions
584 * [Xamarin bindings](https://github.com/martijn00/LottieXamarin)
585 * [NativeScript bindings](https://github.com/bradmartin/nativescript-lottie)
586 * [Appcelerator Titanium bindings](https://github.com/m1ga/ti.animation)
587 * MacOS Support added by [Alex Pawlowski](https://github.com/pawlowskialex)
588
589## Alternatives
5901. Build animations by hand. Building animations by hand is a huge time commitment for design and engineering across Android and iOS. It's often hard or even impossible to justify spending so much time to get an animation right.
5912. [Facebook Keyframes](https://github.com/facebookincubator/Keyframes). Keyframes is a wonderful new library from Facebook that they built for reactions. However, Keyframes doesn't support some of Lottie's features such as masks, mattes, trim paths, dash patterns, and more.
5922. Gifs. Gifs are more than double the size of a bodymovin JSON and are rendered at a fixed size that can't be scaled up to match large and high density screens.
5933. Png sequences. Png sequences are even worse than gifs in that their file sizes are often 30-50x the size of the bodymovin json and also can't be scaled up.
594
595## Why is it called Lottie?
596Lottie is named after a German film director and the foremost pioneer of silhouette animation. Her best known films are The Adventures of Prince Achmed (1926) – the oldest surviving feature-length animated film, preceding Walt Disney's feature-length Snow White and the Seven Dwarfs (1937) by over ten years
597[The art of Lotte Reineger](https://www.youtube.com/watch?v=LvU55CUw5Ck&feature=youtu.be)
598
599## Contributing
600Contributors are more than welcome. Just upload a PR with a description of your changes.
601
602If you would like to add more JSON files feel free to do so!
603
604## Issues or feature requests?
605File github issues for anything that is unexpectedly broken. If an After Effects file is not working, please attach it to your issue. Debugging without the original file is much more difficult. Lottie is developed and maintained by [Brandon Withrow](mailto:brandon.withrow@airbnb.com). Feel free to reach out via email or [Twitter](https://twitter.com/theWithra)
606
607## Roadmap (In no particular order)
608- Add support for interactive animated transitions