• Stars
    star
    1,218
  • Rank 38,490 (Top 0.8 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Render After Effects animations natively on Android, iOS, MacOS and TvOS for Xamarin

LottieXamarin

Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as json with Bodymovin and renders them natively on mobile!

Support

  • Feel free to open an issue. Make sure to use one of the templates!
  • Commercial support is available. Integration with your app or services, samples, feature request, etc. Email: [email protected]
  • Powered by: baseflow.com

Download

Android: NuGet Badge iOS: NuGet Badge Xamarin.Forms: NuGet Badge

For the first time, designers can create and ship beautiful animations without an engineer painstakingly recreating it by hand. They say a picture is worth 1,000 words so here are 13,000:

Example1

Example2

Example3

Community

Example4

All of these animations were created in After Effects, exported with Bodymovin, and rendered natively with no additional engineering effort.

Bodymovin is an After Effects plugin created by Hernan Torrisi that exports After effects files as json and includes a javascript web player. We've built on top of his great work to extend its usage to Android, iOS, and React Native.

Read more about it on our blog post Or get in touch on Twitter (gpeal8) or via [email protected]

Sample App

You can build the sample app yourself or download it from the Play Store. The sample app includes some built in animations but also allows you to load an animation from internal storage or from a url.

Using Lottie for Xamarin.Forms

A normal sample is:

<forms:AnimationView
    x:Name="animationView"
    Animation="LottieLogo1.json"
    AnimationSource="AssetOrBundle"
    Command="{Binding ClickCommand}"
    VerticalOptions="FillAndExpand"
    HorizontalOptions="FillAndExpand" />

All possible options are:

<forms:AnimationView 
    x:Name="animationView"
    Animation="LottieLogo1.json"
    AnimationSource="AssetOrBundle"
    AutoPlay="True"
    CacheComposition="True"
    Clicked="animationView_Clicked"
    Command="{Binding ClickCommand}"
    FallbackResource="{Binding Image}"
    ImageAssetsFolder="Assets/lottie"
    IsAnimating="{Binding IsAnimating}"
    MaxFrame="100"
    MaxProgress="100"
    MinFrame="0"
    MinProgress="0"
    OnAnimationLoaded="animationView_OnAnimationLoaded"
    OnAnimationUpdate="animationView_OnAnimationUpdate"
    OnFailure="animationView_OnFailure"
    OnFinishedAnimation="animationView_OnFinishedAnimation"
    OnPauseAnimation="animationView_OnPauseAnimation"
    OnPlayAnimation="animationView_OnPlayAnimation"
    OnRepeatAnimation="animationView_OnRepeatAnimation"
    OnResumeAnimation="animationView_OnResumeAnimation"
    OnStopAnimation="animationView_OnStopAnimation"
    Progress="{Binding Progress}"
    RepeatCount="3"
    RepeatMode="Restart"
    Scale="1"
    Speed="1"
    VerticalOptions="FillAndExpand"
    HorizontalOptions="FillAndExpand" />

Using Lottie for Xamarin Android

Lottie supports Ice Cream Sandwich (API 14) and above. The simplest way to use it is with LottieAnimationView:

<com.airbnb.lottie.LottieAnimationView
        android:id="@+id/animation_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:lottie_fileName="hello-world.json"
        app:lottie_loop="true"
        app:lottie_autoPlay="true" />

Or you can load it programatically in multiple ways. From a json asset in app/src/main/assets:

LottieAnimationView animationView = FindViewById<LottieAnimationView>(Resource.Id.animation_view);
animationView.SetAnimation("hello-world.json");
animationView.Loop = true;

This method will load the file and parse the animation in the background and asynchronously start rendering once completed.

If you want to reuse an animation such as in each item of a list or load it from a network request JSONObject:

 LottieAnimationView animationView = FindViewById<LottieAnimationView>(Resource.Id.animation_view);
 ...
 LottieComposition composition = LottieComposition.Factory.FromJson(Resources, jsonObject, (composition) => 
 {
     animationView.SetComposition(composition);
     animationView.PlayAnimation();
 });

You can then control the animation or add listeners:

animationView.AddAnimatorUpdateListener(animationListener);
animationView.PlayAnimation();
...
if (animationView.IsAnimating) 
{
    // Do something.
}
...
animationView.Progress = 0.5f;
...
// Custom animation speed or duration.
ValueAnimator animator = ValueAnimator.OfFloat(0f, 1f).SetDuration(500);
animator.Update += (sender, e) => animationView.Progress = (float)e.Animation.AnimatedValue;
animator.Start();
...
animationView.CancelAnimation();

Under the hood, LottieAnimationView uses LottieDrawable to render its animations. If you need to, you can use the the drawable form directly:

LottieDrawable drawable = new LottieDrawable();
LottieComposition.Factory.FromAssetFileName(Context, "hello-world.json", (composition) => {
    drawable.SetComposition(composition);
});

If your animation will be frequently reused, LottieAnimationView has an optional caching strategy built in. Use LottieAnimationView#SetAnimation(String, CacheStrategy). CacheStrategy can be Strong, Weak, or None to have LottieAnimationView hold a strong or weak reference to the loaded and parsed animation.

You can also use the awaitable version of LottieComposition's asynchronous methods:

var composition = await LottieComposition.Factory.FromAssetFileNameAsync(this.Context, assetName);
..
var composition = await LottieComposition.Factory.FromJsonAsync(Resources, jsonObject);
...
var composition = await LottieComposition.Factory.FromInputStreamAsync(this.Context, stream);

Image Support

You can animate images if your animation is loaded from assets and your image file is in a subdirectory of assets. Just call SetImageAssetsFolder on LottieAnimationView or LottieDrawable with the relative folder inside of assets and make sure that the images that bodymovin export are in that folder with their names unchanged (should be img_#). If you use LottieDrawable directly, you must call RecycleBitmaps when you are done with it.

If you need to provide your own bitmaps if you downloaded them from the network or something, you can provide a delegate to do that:

animationView.SetImageAssetDelegate((LottieImageAsset asset) =>
{
   retun GetBitmap(asset);
});

Using Lottie for Xamarin iOS

Lottie supports iOS 8 and above. Lottie animations can be loaded from bundled JSON or from a URL

The simplest way to use it is with LOTAnimationView:

LOTAnimationView animation = LOTAnimationView.AnimationNamed("LottieLogo1");
this.View.AddSubview(animation);
animation.PlayWithCompletion((animationFinished) => {
  // Do Something
});
//You can also use the awaitable version
//var animationFinished = await animation.PlayAsync();

Or you can load it programmatically from a NSUrl

LOTAnimationView animation = new LOTAnimationView(new NSUrl(url));
this.View.AddSubview(animation);

Lottie supports the iOS UIViewContentModes ScaleAspectFit and ScaleAspectFill

You can also set the animation progress interactively.

CGPoint translation = gesture.GetTranslationInView(this.View);
nfloat progress = translation.Y / this.View.Bounds.Size.Height;
animationView.AnimationProgress = progress;

Want to mask arbitrary views to animation layers in a Lottie View? Easy-peasy as long as you know the name of the layer from After Effects

UIView snapshot = this.View.SnapshotView(afterScreenUpdates: true);
lottieAnimation.AddSubview(snapshot, layer: "AfterEffectsLayerName");

Lottie comes with a UIViewController animation-controller for making custom viewController transitions!

#region View Controller Transitioning
public class LOTAnimationTransitionDelegate : UIViewControllerTransitioningDelegate
{
    public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForPresentedController(UIViewController presented, UIViewController presenting, UIViewController source)
    {
        LOTAnimationTransitionController animationController =
            new LOTAnimationTransitionController(
            animation: "vcTransition1",
            fromLayer: "outLayer",
            toLayer: "inLayer");

        return animationController;
    }

    public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForDismissedController(UIViewController dismissed)
    {
        LOTAnimationTransitionController animationController = 
            new LOTAnimationTransitionController(
                animation: "vcTransition2",
                fromLayer: "outLayer",
                toLayer: "inLayer");

        return animationController;
    } 
}
#endregion

If your animation will be frequently reused, LOTAnimationView has an built in LRU Caching Strategy.

Supported After Effects Features

Keyframe Interpolation


  • Linear Interpolation

  • Bezier Interpolation

  • Hold Interpolation

  • Rove Across Time

  • Spatial Bezier

Solids


  • Transform Anchor Point

  • Transform Position

  • Transform Scale

  • Transform Rotation

  • Transform Opacity

Masks


  • Path

  • Opacity

  • Multiple Masks (additive)

Track Mattes


  • Alpha Matte

Parenting


  • Multiple Parenting

  • Nulls

Shape Layers


  • Rectangle (All properties)

  • Ellipse (All properties)

  • Polystar (All properties)

  • Polygon (All properties. Integer point values only.)

  • Path (All properties)

  • Anchor Point

  • Position

  • Scale

  • Rotation

  • Opacity

  • Group Transforms (Anchor point, position, scale etc)

  • Multiple paths in one group

Stroke (shape layer)


  • Stroke Color

  • Stroke Opacity

  • Stroke Width

  • Line Cap

  • Dashes

Fill (shape layer)


  • Fill Color

  • Fill Opacity

Trim Paths (shape layer)


  • Trim Paths Start

  • Trim Paths End

  • Trim Paths Offset

Performance and Memory

  1. If the composition has no masks or mattes then the performance and memory overhead should be quite good. No bitmaps are created and most operations are simple canvas draw operations.
  2. If the composition has mattes, 2-3 bitmaps will be created at the composition size. The bitmaps are created automatically by lottie when the animation view is added to the window and recycled when it is removed from the window. For this reason, it is not recommended to use animations with masks or mattes in a RecyclerView because it will cause significant bitmap churn. In addition to memory churn, additional bitmap.eraseColor() and canvas.drawBitmap() calls are necessary for masks and mattes which will slow down the performance of the animation. For small animations, the performance hit should not be large enough to be obvious when actually used.
  3. If you are using your animation in a list, it is recommended to use a CacheStrategy in LottieAnimationView.setAnimation(String, CacheStrategy) so the animations do not have to be deserialized every time.

Try it out

Clone this repository and run the LottieSample module to see a bunch of sample animations. The JSON files for them are located in LottieSample/src/main/assets and the orignal After Effects files are located in /After Effects Samples

The sample app can also load json files at a given url or locally on your device (like Downloads or on your sdcard).

Community Contributions

Community Contributors

Alternatives

  1. 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.
  2. Facebook 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.
  3. 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.
  4. 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.

Why is it called Lottie?

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

Contributing

Contributors are more than welcome. Just upload a PR with a description of your changes. Lottie uses Facebook screenshot tests for Android to identify pixel level changes/breakages. Please run ./gradlew --daemon recordMode screenshotTests before uploading a PR to ensure that nothing has broken. Use a Nexus 5 emulator running Lollipop for this. Changed screenshots will show up in your git diff if you have.

If you would like to add more JSON files and screenshot tests, feel free to do so and add the test to LottieTest.

Issues or feature requests?

File 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.

To build the source code from command line

  • msbuild Lottie.sln /t:restore
  • msbuild Lottie.sln /p:Configuration=Release

More Repositories

1

PhotoView

Implementation of ImageView for Android that supports zooming, by various touch gestures.
Java
18,771
star
2

flutter_cached_network_image

Download, cache and show images in a flutter app
Dart
2,426
star
3

flutter-permission-handler

Permission plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check permissions.
Dart
2,020
star
4

flutter-geolocator

Android and iOS Geolocation plugin for Flutter
Dart
1,239
star
5

XamarinMediaManager

Cross platform Xamarin plugin to play and control Audio and Video
C#
766
star
6

flutter_cache_manager

Generic cache manager for flutter
Dart
749
star
7

XF-Material-Library

A Xamarin Forms library for implementing Material Design
C#
647
star
8

octo_image

A multifunctional Flutter image widget
Dart
156
star
9

ExoPlayerXamarin

Xamarin bindings library for the Google ExoPlayer library
C#
153
star
10

Chameleon

Chameleon is a flexible media player build with Xamarin.Forms
C#
152
star
11

flutter-geocoding

A Geocoding plugin for Flutter
Dart
135
star
12

Xamarin-Sidebar

A slideout navigation control for Xamarin.iOS
C#
113
star
13

screenrecorder

Flutter package which can be used to record flutter widgets
Dart
64
star
14

FoldingCell

FoldingCell is an expanding content cell inspired by folding paper material
C#
55
star
15

flutter-permission-plugins

This repo contains a collection of permission related Flutter plugins which can be used to request permissions to access device resources in a cross-platform way.
Dart
52
star
16

MvxForms

Sample App with Xamarin.Forms and MvvmCross
C#
47
star
17

HugoStructuredData

Collection of structured data snippets in Google preferred JSON-LD format, with support for Hugo
HTML
42
star
18

flutter-contacts-plugin

Contact plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to read, create and update contacts from the address book.
Dart
40
star
19

NavigationTabBarXamarin

Navigation tab bar with colorful interactions for Xamarin Android
C#
39
star
20

InfiniteCycleViewPagerXamarin

Infinite cycle ViewPager with two-way orientation and interactive effect.
C#
36
star
21

XamarinItemTouchHelper

Basic example of using ItemTouchHelper to add drag & drop and swipe-to-dismiss to RecyclerView for Xamarin
C#
36
star
22

VlcXamarin

Xamarin.Android bindings for VLC player
C#
34
star
23

flutter-google-api-availability

Check the availability of Google Play services on the current device
Dart
34
star
24

NavigationTabStripXamarin

Navigation tab strip with smooth interaction
C#
24
star
25

FantasySlideXamarin

Another sliding menu base on DrawerLayout
C#
20
star
26

DiagonalLayoutXamarin

With Diagonal Layout explore new styles and approaches on material design
C#
19
star
27

LoaderViewXamarin

Library that enables TextView of ImageView to show loading animation while waiting for the text and image get loaded
C#
17
star
28

flutter-video-bloc

Dart
16
star
29

flutter_wizard

A library that makes it easy for you to create your own custom wizard.
Dart
16
star
30

FloatingNavigationView

A simple Floating Action Button that shows an anchored Navigation View
C#
16
star
31

flutter-essentials

Essential cross platform APIs for your Flutter apps
Dart
16
star
32

MaterialDesignHelpers

Default colors and dimens per Material Design guidelines and Android Design guidelines inside one library.
C#
13
star
33

GuardedActions

A library to increase the error handling, testability and reusability for all your MVVM driven apps!
C#
13
star
34

HoverXamarin

A floating menu library for Xamarin Android.
C#
12
star
35

FlipShareXamarin

It's a flip way to show share widget.
C#
11
star
36

AndroidSlidingUpPanelXamarin

This library provides a simple way to add a draggable sliding up panel to your Android app
C#
11
star
37

byteplot

A Dart command-line tool for Flutter to make your life easier
Dart
10
star
38

FFmpegMediaMetadataRetrieverXamarin

FFmpegMediaMetadataRetriever provides a unified interface for retrieving frame and meta data from an input media file.
C#
10
star
39

full-stack-on-rust

Source code and documentation for our 'full stack on rust' meetup on 29-9-2022
Rust
8
star
40

InteractiveMediaAdsXamarin

IMA Android SDK v3 for Xamarin
C#
8
star
41

AutoLinkTextViewXamarin

AutoLinkTextView is TextView that supports Hashtags (#), Mentions (@) , URLs (http://), Phone and Email automatically detecting and ability to handle clicks.
C#
8
star
42

GoogleVRXamarin

Xamarin bindings library for the Google VR library
C#
8
star
43

cheat-sheets

This repo contains a set of cheat sheets often used by the Baseflow crew.
8
star
44

flutter-blues

Flutter plugin to provide easy access to platform specific Bluetooth low energy services
Dart
7
star
45

flutter_swipe_detector

A Flutter package to detect your swipe directions and provides you with callbacks to handle them.
Dart
7
star
46

flutter_uwb

A Flutter plugin for working with Ultra Wide Band sensors.
Dart
7
star
47

stellar-rust-sdk

Welcome to the Rust Stellar SDK repository! This project aims to empower developers with a robust Rust SDK for the Stellar cryptocurrency network. Leverage Rust's performance and security advantages to build efficient and scalable applications on Stellar. Join us in shaping the future of blockchain development with Stellar and Rust integration.
Rust
7
star
48

WaveSideBarXamarin

An Index Side Bar With Wave Effect
C#
6
star
49

baseflow_plugin_template

Template for the Baseflow flutter plugins
Dart
5
star
50

VerticalViewPagerXamarin

Vertically ViewPager and vertically transformer for Xamarin Android
C#
5
star
51

flutter_state_management_demo

A demonstration app showcasing the Baseflow way of State Management in Flutter
Dart
4
star
52

AutoscaleEditTextXamarin

AutoscaleEditText bindings for Xamarin Android
C#
4
star
53

flutter-style-guide

A Flutter style-guide example app
Dart
3
star
54

DSTV.Net

A basic Tekla DSTV NC file parser written in C#
C#
3
star
55

flutter-meetup

Sheets and samples for our flutter meetups
Dart
3
star
56

konami_detector

A package to detect your konami codes and executes the provided callbacks.
Dart
3
star
57

terraform-demo

Code and descriptions for the demo on the 14th July 2023
HCL
2
star
58

service_manager

A Flutter plugin to manage the state of platform specific services (e.g. location services).
Dart
2
star
59

flutter_ioc

A standard interface providing inversion of control services to Dart or Flutter applications.
Dart
2
star
60

EllipsizeTextViewXamarin

The EllipsizeTextView extends TextView, support omit (Ellipsize/Ellipsis) redundant characters in multiple lines situtation.
C#
2
star
61

GuardedActions.Samples

Contains sample project on how to implement the GuardedActions package.
C#
1
star