Using Codegen
Consuming Bodymovin JSON files is the standard way of displaying Lottie animations on Web, Android, and iOS. However, this approach comes with the overhead of having to parse and translate JSON in your application’s process. You can get significant performance benefits by having Lottie-Windows generate the animation code as a C# or C++ class ahead of time, which may be used instead of the LottieVisualSource. Both approaches, JSON and Codegen, have the same visual outcome but different workflows and benefits.
Generating a C# or C++ class from JSON
To generate a C# or C++ file from JSON use the LottieGen command-line tool.
In your command-line interface, install the LottieGen tool from nuget:
dotnet tool install -g LottieGen
Generate classes in your desired language as follows:
LottieGen -InputFile LottieLogo1.json -Language cs
For additional information about additional options including optimizations, use LottieGen -Help
.
Using the Codegen File
Add the generated file, LottieLogo1.cs, to your project by following steps similar to those outlined previously. Ensure that the Build Action for all codegen C# or C++ files is set to Compile.
By default, all codegen classes are generated in the AnimatedVisuals namespace. Modify your Page.xaml to include the namespace:
xmlns:animatedvisuals="using:AnimatedVisuals"
Install the Microsoft.UI.Xaml nuget package which contains the AnimatedVisualPlayer element. Modify your Page.xaml to include the namespace:
xmlns:controls="using:Microsoft.UI.Xaml.Controls"
Instantiate the AnimatedVisualPlayer element and configure its Source as follows:
<Border Style="{StaticResource LottiePlayer}"> <!--AnimatedVisualPlayer with AutoPlay--> <controls:AnimatedVisualPlayer x:Name="LottiePlayer"> <!--Codegen class AnimatedVisuals/LottieLogo1.cs--> <animatedvisuals:LottieLogo1/> </controls:AnimatedVisualPlayer> </Border>
This should result in a looping Lottie animation that is visually identical to our earlier approach of using a JSON file:
Resources
- Source code for sample: getting started with Codegen
- The resulting page in the Lottie Samples application
- LottieGen CLI tool
- Lottie Viewer application for codegen and previewing JSON files
- A comparison of JSON verus Codegen
- Help + feedback