編輯

共用方式為


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.

  1. In your command-line interface, install the LottieGen tool from nuget:

    dotnet tool install -g LottieGen
    
  2. 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

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

  2. By default, all codegen classes are generated in the AnimatedVisuals namespace. Modify your Page.xaml to include the namespace:

    xmlns:animatedvisuals="using:AnimatedVisuals"
    
  3. 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"
    
  4. 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:

Autoplay Gif

Resources