Search code examples
c#.netmauilottie

How to programatically start and stop lottie animations in .NET Maui


I would like to be able to play an animation in my .NET task project whenever I add a task.

Right now I'm able to use SkiaSharp.Extended.UI.Maui to load and animate a lottie file. I can also trigger an animation with a tapgesture. It plays the animation but when I press again it does not play the animation again or it keeps repeating the animation without stopping.

I tried using the property repeatcount. I tried setting it to -1(keep repeating), 0, 1

I have also tried using the duration, isvisible, and isenabled along with a timer. An event gets fired when the duration of the animation has passed and I hide the animation again. That works however only once. I can't get it to run again after that.

Xaml

                <skia:SKLottieView
                        x:Name="animatedPlusIcon"
                        Source="WhiteCheck.json"
                        HeightRequest="150"
                        WidthRequest="150"
                        RepeatCount="0"
                        IsAnimationEnabled="True">
                <skia:SKLottieView.GestureRecognizers>
                    <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
                </skia:SKLottieView.GestureRecognizers>
            </skia:SKLottieView>

Code behind

    void TapGestureRecognizer_Tapped(System.Object sender, System.EventArgs e)
{
    animatedPlusIcon.IsAnimationEnabled = true;
}

Solution

  • The only workaround i found is: Each time you create a new task, you could remove Lottie first and then add it again with custom settings. Such like the following:

    In xaml, add it in a mystack

    <StackLayout x:Name="mystack">
        <skl:SKLottieView
        .... 
        </skl:SKLottieView>
    </StackLayout>
    

    Each time you create a task, first remove it and then add it:

    (mystack as StackLayout).Clear();
    SKLottieView myanimatedview = new SKLottieView();
    var a = new SKFileLottieImageSource();
    a.File = "dotnetbot.json";
    myanimatedview.Source = a;
    myanimatedview.RepeatCount = 3;
    (mystack as StackLayout).Add(myanimatedview);
    

    For more info, you could refer to SKLottieView. As we can see there is not many APIs for us as it is still a perview. You could also report an issue on Github: SKLottie Issues on Github

    Hope it works for you.