Flutter 帧动画支持倒放

import 'package:flutter/material.dart';

class FrameAnimCtrl extends StatefulWidget {

  ///每一帧的间隔 毫秒

  final int interval;

  //循环播放

  final bool loop;

  //没有办法自己销毁自己, 这里选择回调函数给父节点

  //只播放一次时, 完成回调

  final Function onend;

  //图片集合

  final List<String> imageCaches;

  final double width;

  final double height;

  final Color backColor;

  //逆序播放(先正 后反)

  final bool reverse;

  FrameAnimCtrl(

      {Key key,

      this.interval = 100,

      this.loop = true,

      this.imageCaches,

      this.width,

      this.height,

      this.backColor,

      this.onend,

      this.reverse = false})

      : assert(imageCaches != null),

        super(key: key);

  @override

  _FrameAnimCtrlState createState() => _FrameAnimCtrlState();

}

class _FrameAnimCtrlState extends State<FrameAnimCtrl> {

  bool _disposed;

  Duration _duration;

  int _imageIndex;

  Container _container;

  bool isPlay;

  //当前初始化是正序

  bool curfx = true;

  @override

  void initState() {

    super.initState();

    _disposed = false;

    _duration = Duration(milliseconds: widget.interval);

    _imageIndex = 0;

    _container = Container(height: widget.height, width: widget.width);

    isPlay = true;

    _updateImage();

  }

  void _updateImage() {

    if (_disposed || widget.imageCaches.isEmpty) {

      return;

    }

    setState(() {

      if (_imageIndex >= widget.imageCaches.length - 1) {

        if (widget.reverse == false) {

          curfx = true;

          _imageIndex = 0;

          if (widget.loop == false) {

            isPlay = false;

            if (widget.onend != null) {

              widget.onend();

            }

            return;

          }

        } else {

          curfx = false;

        }

      }

      //逆序播放回来了

      else if (_imageIndex == 0 && curfx == false) {

        curfx = true;

        if (widget.loop == false) {

          isPlay = false;

          if (widget.onend != null) {

            widget.onend();

          }

          return;

        }

      }

      _container = Container(

          color: widget.backColor,

          child: Image.asset(widget.imageCaches[_imageIndex]),

          height: widget.height,

          width: widget.width);

      if (curfx == true) {

        _imageIndex++;

      } else {

        _imageIndex--;

      }

    });

    if (isPlay == false) {

      return;

    }

    Future.delayed(_duration, () {

      _updateImage();

    });

  }

  @override

  void dispose() {

    super.dispose();

    _disposed = true;

    widget.imageCaches.clear();

  }

  @override

  Widget build(BuildContext context) {

    return _container;

  }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容