This is Lottie for Qt. It was not invented by us and most of the code was directly ported from the iOS Objective-C code.
- Introduction
- Installing Lottie
- Sample App
- Code Examples
- Debugging Lottie
- Changing Animations At Runtime
- Animated Controls and Switches
- Adding Subviews to Animation
- Supported After Effects Features
- Currently Unsupported After Effects Features
- Community Contributions
- Alternatives
- Why is it called Lottie?
- Contributing
- Issues or feature requests?
Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as json with bodymovin and renders the vector animations natively all platforms using the QtQuick scene graph!
For the first time, designers can create and ship beautiful animations without an engineer painstakingly recreating it by hand. Since the animation is backed by JSON they are extremely small in size but can be large in complexity! Animations can be played, resized, looped, sped up, slowed down, reversed, and even interactively scrubbed. Lottie can play or loop just a portion of the animation as well, the possibilities are endless! Animations can even be changed at runtime in various ways! Change the color, position or any keyframable value! Lottie also supports native UIViewController Transitions out of the box!
Here is just a small sampling of the power of Lottie
You can pull the Lottie Github Repo and include the Lottie.xcodeproj to build a dynamic or static library.
TBD
Clone this repo and try out the Sample App The repo can build a macOS Example and an iOS Example
The iOS Example App demos several of the features of Lottie
The animation Explorer allows you to scrub, play, loop, and resize animations. Animations can be loaded from the app bundle or from Lottie Files using the built in QR Code reader.
Lottie animations can be loaded from bundled JSON or from a URL To bundle JSON just add it and any images that the animation requires to your target in xcode.
LOTAnimationView *animation = [LOTAnimationView animationNamed:@"Lottie"];
[self.view addSubview:animation];
[animation playWithCompletion:^(BOOL animationFinished) {
// Do Something
}];
If you are working with multiple bundles you can use.
LOTAnimationView *animation = [LOTAnimationView animationNamed:@"Lottie" inBundle:[NSBundle YOUR_BUNDLE]];
[self.view addSubview:animation];
[animation playWithCompletion:^(BOOL animationFinished) {
// Do Something
}];
Or you can load it programmatically from a NSURL
LOTAnimationView *animation = [[LOTAnimationView alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
[self.view addSubview:animation];
Lottie supports the iOS UIViewContentModes
aspectFit, aspectFill and scaleFill
You can also set the animation progress interactively.
CGPoint translation = [gesture getTranslationInView:self.view];
CGFloat progress = translation.y / self.view.bounds.size.height;
animationView.animationProgress = progress;
Or you can play just a portion of the animation:
[lottieAnimation playFromProgress:0.25 toProgress:0.5 withCompletion:^(BOOL animationFinished) {
// Do Something
}];
Lottie has a couple of debugging features to know about. When an animation is loaded unsupported features are logged out in the console with their function names.
If you checkout LOTHelpers.h you will see two debug flags. ENABLE_DEBUG_LOGGING
and ENABLE_DEBUG_SHAPES
.
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.
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.
LOTAnimationView provides - (void)logHierarchyKeypaths
which will recursively log all settable keypaths for the animation. This is helpful for changing animationations at runtime.
Not only can you change animations at runtime with Lottie, you can also add custom UI to a LOTAnimation at runtime. The example below shows some advance uses of this to create a dynamic image loader.
The 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.
Now, 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!
Here, 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.
Pretty powerful eh?
Check out the code below for an example!
import UIKit
import Lottie
class ViewController: UIViewController {
var animationView: LOTAnimationView = LOTAnimationView(name: "SpinnerSpin");
override func viewDidLoad() {
super.viewDidLoad()
// Setup our animaiton view
animationView.contentMode = .scaleAspectFill
animationView.frame = CGRect(x: 20, y: 20, width: 200, height: 200)
self.view.addSubview(animationView)
// Lets change some of the properties of the animation
// We arent going to use the MaskLayer, so lets just hide it
animationView.setValue(0, forKeypath: "MaskLayer.Ellipse 1.Transform.Opacity", atFrame: 0)
// All of the strokes and fills are white, lets make them DarkGrey
animationView.setValue(UIColor.darkGray, forKeypath: "OuterRing.Stroke.Color", atFrame: 0)
animationView.setValue(UIColor.darkGray, forKeypath: "InnerRing.Stroke.Color", atFrame: 0)
animationView.setValue(UIColor.darkGray, forKeypath: "InnerRing.Fill.Color", atFrame: 0)
// Lets turn looping on, since we want it to repeat while the image is 'Downloading'
animationView.loopAnimation = true
// Now play from 0 to 0.5 progress and loop indefinitely.
animationView.play(fromProgress: 0, toProgress: 0.5, withCompletion: nil)
// Lets simulate a download that finishes in 4 seconds.
let dispatchTime = DispatchTime.now() + 4.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.simulateImageDownloaded()
}
}
func simulateImageDownloaded() {
// Our downloaded image
let image = UIImage(named: "avatar.jpg")
let imageView = UIImageView(image: image)
// We want the image to show up centered in the animation view at 150Px150P
// Convert that rect to the animations coordinate space
// The origin is set to -75, -75 because the origin is centered in the animation view
let imageRect = animationView.convert(CGRect(x: -75, y: -75, width: 150, height: 150), toLayerNamed: nil)
// Setup our image view with the rect and add rounded corners
imageView.frame = imageRect
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = imageRect.width / 2;
// Now we set the completion block on the currently running animation
animationView.completionBlock = { (result: Bool) in ()
// Add the image view to the layer named "TransformLayer"
self.animationView.addSubview(imageView, toLayerNamed: "TransformLayer", applyTransform: true)
// Now play the last half of the animation
self.animationView.play(fromProgress: 0.5, toProgress: 1, withCompletion: { (complete: Bool) in
// Now the animation has finished and our image is displayed on screen
print("Image Downloaded and Displayed")
})
}
// Turn looping off. Once the current loop finishes the animation will stop
// and the completion block will be called.
animationView.loopAnimation = false
}
}
Lottie can do more than just play beautiful animations. Lottie allows you to change animations at runtime.
Its easy to create the four switches and play them:
let animationView = LOTAnimationView(name: "toggle");
self.view.addSubview(animationView)
animationView.frame.origin.x = 40
animationView.frame.origin.y = 20
animationView.autoReverseAnimation = true
animationView.loopAnimation = true
animationView.play()
let animationView2 = LOTAnimationView(name: "toggle");
self.view.addSubview(animationView2)
animationView2.frame.origin.x = 40
animationView2.frame.origin.y = animationView.frame.maxY + 4
animationView2.autoReverseAnimation = true
animationView2.loopAnimation = true
animationView2.play()
let animationView3 = LOTAnimationView(name: "toggle");
self.view.addSubview(animationView3)
animationView3.frame.origin.x = 40
animationView3.frame.origin.y = animationView2.frame.maxY + 4
animationView3.autoReverseAnimation = true
animationView3.loopAnimation = true
animationView3.play()
let animationView4 = LOTAnimationView(name: "toggle");
self.view.addSubview(animationView4)
animationView4.frame.origin.x = 40
animationView4.frame.origin.y = animationView3.frame.maxY + 4
animationView4.autoReverseAnimation = true
animationView4.loopAnimation = true
animationView4.play()
animationView2.setValue(UIColor.green, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
animationView3.setValue(UIColor.red, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
animationView4.setValue(UIColor.orange, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
[animationView2 setValue:[UIColor greenColor] forKeypath:@"BG-On.Group 1.Fill 1.Color" atFrame:@0];
The keyPath is a dot separated path of layer and property names from After Effects.
LOTAnimationView provides - (void)logHierarchyKeypaths
which will recursively log all settable keypaths for the animation.
"BG-On.Group 1.Fill 1.Color"
animationView2.setValue(UIColor.green, forKeypath: "BG-On.Group 1.Fill 1.Color", atFrame: 0)
animationView2.setValue(UIColor.red, forKeypath: "BG-Off.Group 1.Fill 1.Color", atFrame: 0)
Lottie 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.
Lottie also has a custom subclass of UIControl for creating custom animatable interactive controls.
Currently 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.
You initialize the switch either using the conveneince method or by supplying the animation directly.
// Convenience
LOTAnimatedSwitch *toggle1 = [LOTAnimatedSwitch switchNamed:@"Switch"];
// Manually
LOTComposition *comp = [LOTComposition animationNamed:@"Switch"];
LOTAnimatedSwitch *toggle1 = [[LOTAnimatedSwitch alloc] initWithFrame:CGRectZero];
[toggle1 setAnimationComp:comp];
You can also specify a specific portion of the animation's timeline for the On and Off animation.
By default LOTAnimatedSwitch
will play the animation forward for On and backwards for off.
Lets say that the supplied animation animates ON from 0.5-1 progress and OFF from 0-0.5:
/// On animation is 0.5 to 1 progress.
[toggle1 setProgressRangeForOnState:0.5 toProgress:1];
/// Off animation is 0 to 0.5 progress.
[toggle1 setProgressRangeForOffState:0 toProgress:0.5];
Also, 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.
Lets 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.
Now in code we can associate UIControlState
with these layers
// Specify the layer names for different states
[statefulSwitch setLayerName:@"Button" forState:UIControlStateNormal];
[statefulSwitch setLayerName:@"Disabled" forState:UIControlStateDisabled];
// Changes visual appearance by switching animation layer to "Disabled"
statefulSwitch.enabled = NO;
// Changes visual appearance by switching animation layer to "Button"
statefulSwitch.enabled = YES;
- Linear Interpolation
- Bezier Interpolation
- Hold Interpolation
- Rove Across Time
- Spatial Bezier
- Transform Anchor Point
- Transform Position
- Transform Scale
- Transform Rotation
- Transform Opacity
- Path
- Opacity
- Multiple Masks (additive, subtractive and intersection)
- Alpha Matte
- Multiple Parenting
- Nulls
- Anchor Point
- Position
- Scale
- Rotation
- Opacity
- Path
- Group Transforms (Anchor point, position, scale etc)
- Rectangle (All properties)
- Eclipse (All properties)
- Multiple paths in one group
- Even-Odd winding paths
- Reverse Fill Rule
- Stroke Color
- Stroke Opacity
- Stroke Width
- Line Cap
- Dashes (Now Animated!)
- Fill Color
- Fill Opacity
- Trim Paths Start
- Trim Paths End
- Trim Paths Offset
- Supports repeater transforms
- Offset currently not supported.
- Support for Linear Gradients
- Support for Radial Gradients
- Supported! Theres a known bug if the roundness is greater than 100 percent.
- Precomps
- Image Layers
- Shape Layers
- Null Layers
- Solid Layers
- Parenting Layers
- Alpha Matte Layers
- Merge Shapes
- Alpha Inverted Masks
- Trim Shapes Individually feature of Trim Paths
- Expressions
- 3d Layer support
- Time remapping / Layer Reverse
- Layer Blend Modes
- Layer Effects
- Build animations by hand. Building animations by hand is a huge time commitment for design and engineering, even with QtQuick. It's often hard or even impossible to justify spending so much time to get an animation right.
- 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.
- 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.
Lottie 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 The art of Lotte Reineger
Contributors are more than welcome. Just upload a PR with a description of your changes.
If you would like to add more JSON files feel free to do so!
TBD
- Watermelon example renders strangely
- Switch example renders strangely
- Dashes not tested
- Masking not implemented
- Gradients not implemented
- Memory leaks not checked yet
- Every frame recreates all scene graph nodes
- Line caps are sometimes not round enough. This is caused by scaling though the scene graph. Should be changed to value delegates.
- No "autoReverseAnimation" property
- No LOTAnimatableSwitch implementation for now
- Typewriter cursor is not blinking
- playToFrame and other helpers are missing