Using Lottie Animations In Xamarin.Forms

Introduction

In the last few years, an interesting animation format has become extremely popular among designers and developers, and it is a format produced by the famous Adobe After Effects design suite. This format is not actually a proprietary one, rather it is JSON.

Adobe After Effects can produce files in a specialized JSON format containing the design for animated illustrations. In order to render these JSON animations, several libraries exist, but the most important is called Lottie, which is offered by Airbnb. One of its major advantages is that Lottie files are generally much smaller than an equivalent animated .gif file.

For Xamarin.Forms, a Lottie implementation also exists and allows you to play beautiful animated JSON illustrations in your mobile apps.

Lottie for Xamarin.Forms

A Lottie open-source implementation also exists for Xamarin.Forms, and it is very easy to use. For the next example, create a new, blank Xamarin.Forms project and open the NuGet Package Manager user interface. The NuGet package you need to install is called Com.AirBnb.Xamarin.Forms.Lottie as shown in this figure:

Using Lottie animations in Xamarin.Forms

The way your app consumes Lottie animations depends on the source of the animations themselves. If your team has designers that produce Lottie JSON files, you will add such files into the solution as follows:

  • • For Android, your JSON files must be added into the Assets folder, and the Build Action must be set as AndroidResource.
  • • For iOS, your JSON files must be added into the Resources folder, and the Build Action must be set as BundleResource.

If Lottie animations are instead hosted on a web server, either public or private, the animation can be simply consumed by passing its URI to the Lottie view. A very nice and popular source for Lottie animations is the Lottiefiles.com website. On this site, you can find both free and paid animations, illustrations, icons, and much more. For the current example, I will use the JSON animation included in the Lottie library repository, which is already included inside the companion code for your convenience, but you are free to use whatever animation you want.

Implementing the viewer

The Lottie library provides a new view called AnimationView. Before you can use it in your XAML, you need to add the following XML namespace declaration at the ContentPage level:

xmlns:lottie="clr-namespace:Lottie.Forms;assembly=Lottie.Forms"

In its simplest form, the AnimationView can be declared as follows:

<lottie:AnimationView
    HorizontalOptions="FillAndExpand"
    VerticalOptions="FillAndExpand"
    x:Name="animationView"
    Animation="lottielogo.json"
    AnimationSource="AssetOrBundle"
    AutoPlay="True" RepeatMode="Restart"
RepeatCount="3"/>

The AnimationSource property specifies where the JSON animation comes from. In this case, AssetOrBundle means the animation is a local file. Other options can be Url, Stream, and Json. The first two are self-explanatory; the latter allows you to bind a string object containing the JSON. With AssetOrBundle, Url, and Stream, you use the Animation property to specify the animation file name; with Json, you need to assign a property called AnimationJson. In the example, AutoPlay is set as True, and the animation will restart (RepeatMode) three times (RepeatCount). RepeatMode can also be set with Reverse and Infinite, and the latter helps you avoid the need of setting the RepeatCount property. If you run the sample app, you will see the Lottie animation being played on your device. The following figure shows a static frame of the animation, but it will be animating on a physical device and/or simulator.

The Lottie library allows you to control with more granularity the way the animation is played, and this is discussed in the next section.

Controlling the animation

The Lottie library provides methods and properties that allow developers to control the flow of the animations. Methods that you can use to manage the animations are PlayAnimation, PauseAnimation, and StopAnimation, which are self-explanatory. There are also events that can be useful to understand the status of playing, such as:

  • OnAnimationLoaded, raised when the animation has been loaded by the AnimationView.
  • OnAnimationUpdated, raised when playing moves on.
  • OnFailure, raised when loading or playing the application fails.
  • A series of self-explanatory events that are raised in the different phases of playing the animation, such as OnPlayAnimation, OnPauseAnimation, OnFinishedAnimation, OnRepeatAnimation, OnResumeAnimation, and OnStopAnimation.

You can also control the user interaction via the Clicked event, which is raised when the user taps the animation, and with the Command property, which you use instead of the Clicked event if your implementation is based on the Model-View-ViewModel pattern.

Especially when your animations are loaded from a web resource via URI, failures in loading the animation can happen, and the OnFailure event is raised. Think of connectivity issues, or of an animation that is not compatible with the After Effects JSON structure. In this case, the AnimationView.FallbackSource property comes to help. It is of type ImageSource and can be assigned with a static image that will be displayed in case of errors. Additional properties of interest are:

  • Duration, of type long, which represents the duration of the animation expressed in frames/frame rate * 1,000.
  • Progress, MaxProgress, and MinProgress, all of type float, which respectively represents the progress of the animation, the final point at which the animation must stop playing, and the starting point at which the animation should start playing.
  • Frame, of type int, which allows for setting the progress of the animation at an exact frame.
  • MaxFrame and MinFrame, both of type int, which respectively allow setting the exact frame where the animation is set to stop and start.
  • IsAnimating, of type bool, which returns true if the animation is being played.
  • Speed, of type int, which allows setting the speed of the animation. The default is 1.

The following XAML shows a simple example in which you prepare the AnimationView for programmatic control:

<StackLayout>
  <lottie:AnimationView x:Name="animationView" Animation="lottielogo.json" AnimationSource="AssetOrBundle" FallbackResource="Error.png" AutoPlay="False" />
  <StackLayout Orientation="Horizontal" Margin="20,0,0,0">
    <Button x:Name="PlayButton" Clicked="PlayButton_Clicked" Text="Play" />
    <Button x:Name="PauseButton" Clicked="PauseButton_Clicked" Text="Pause" />
    <Button x:Name="StopButton" Clicked="StopButton_Clicked" Text="Stop" />
  </StackLayout>
</StackLayout>

Notice how the FallbackResource property is assigned with an image file that will be shown in case the animation fails to load. As you would expect, the event handlers that control playing the animation are very easy and look like the following:

private void PlayButton_Clicked(object sender, EventArgs e) {
    animationView.PlayAnimation();
}
private void PauseButton_Clicked(object sender, EventArgs e) {
    animationView.PauseAnimation();
}
private void StopButton_Clicked(object sender, EventArgs e) {
    animationView.StopAnimation();
}

In this way, you can satisfy even the more complex design requirements, while at the same time enriching the application behavior.


Similar Articles