You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Xamarin.Forms与Lottie,如何实现AnimationView点击切换正反向播放?

实现Lottie AnimationView点击切换正反向播放(Xamarin.Forms 5.0 + Lottie 4.1.0)

核心思路是通过状态变量记录当前播放方向,每次点击时先终止当前动画,再根据状态切换播放逻辑:

  1. 定义状态标记:用布尔变量_isPlayingForward记录当前播放方向,初始值设为true(默认正向播放)。
  2. 处理点击事件:每次点击时先停止当前动画,再根据状态调用对应播放方法,最后切换状态标记。

代码后台实现示例

XAML布局

<forms:AnimationView x:Name="LottieAnimation" 
                     Animation="your_animation_file.json"
                     Clicked="OnAnimationClicked" />

C#后台逻辑

private bool _isPlayingForward = true;

private void OnAnimationClicked(object sender, EventArgs e)
{
    // 停止当前动画,确保切换方向前状态重置
    LottieAnimation.CancelAnimation();

    if (_isPlayingForward)
    {
        // 触发正向播放
        LottieAnimation.PlayAnimation();
    }
    else
    {
        // 触发反向播放
        LottieAnimation.PlayAnimationReverse();
    }

    // 切换播放方向状态
    _isPlayingForward = !_isPlayingForward;
}

MVVM模式实现示例(Command绑定)

如果采用MVVM架构,可通过绑定Command处理点击逻辑:

ViewModel代码

using Xamarin.Forms;
using Com.Airbnb.Xamarin.Forms.Lottie;

public class YourViewModel : BindableObject
{
    private bool _isPlayingForward = true;
    private AnimationView _animationView;

    public ICommand ToggleAnimationCommand { get; }

    public YourViewModel(AnimationView animationView)
    {
        _animationView = animationView;
        ToggleAnimationCommand = new Command(ExecuteToggleAnimation);
    }

    private void ExecuteToggleAnimation()
    {
        _animationView.CancelAnimation();

        if (_isPlayingForward)
        {
            _animationView.PlayAnimation();
        }
        else
        {
            _animationView.PlayAnimationReverse();
        }

        _isPlayingForward = !_isPlayingForward;
    }
}

XAML绑定配置

<ContentPage.BindingContext>
    <local:YourViewModel x:Arguments="{x:Reference LottieAnimation}" />
</ContentPage.BindingContext>

<forms:AnimationView x:Name="LottieAnimation" 
                     Animation="your_animation_file.json"
                     Command="{Binding ToggleAnimationCommand}" />

关键注意点

  • CancelAnimation()可安全调用,无论当前动画是否处于播放状态,都能重置动画初始状态。
  • Lottie 4.1.0版本中PlayAnimation()默认执行正向播放,PlayAnimationReverse()直接触发反向播放,无需额外配置播放区间。

内容的提问来源于stack exchange,提问作者dembo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:55:16