【问题标题】:How can we control animated gif image using button?我们如何使用按钮控制动画 gif 图像?
【发布时间】:2018-09-11 08:48:36
【问题描述】:

我想通过单击按钮来控制 gif 动画,即,如果我按下“单击我”按钮动画开始并再次按下动画应该停止。我正在参考这个问题How to display an animated picture in Flutter?
我不想将 gif 图像拆分为帧,我必须只使用一个 gif 图像并仅控制它。这是我的代码。

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<int> _animation;

  @override
  void initState() {
    _controller = new AnimationController(
        vsync: this, duration: const Duration(seconds: 3))
      ..stop();
    _animation = new IntTween(begin: 0, end: 7).animate(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new AnimatedBuilder(
            animation: _animation,
            builder: (BuildContext context, Widget child) {
              String frame = _animation.value.toString().padLeft(0, '0');
              return new Image.asset(
                'assets/lips.gif',
                gaplessPlayback: true,
              );
            },
          ),
          new RaisedButton(
            child: new Text('click me'),
            onPressed: () {
              if (_controller.isAnimating) {
                _controller.stop();
              } else {
                _controller.repeat();
              }
            },
          ),
        ],
      ),
    );
  }
}

【问题讨论】:

标签: dart flutter


【解决方案1】:

Flutter 目前支持使用Image 小部件播放GIF 文件。

但仍然没有简单的方法来控制(例如暂停和播放)GIF 文件。在控制它时,一种解决方法是使用包。 Lottie for Flutter 可用于实现此行为。

解决方法:

  • 将您的 gif 转换为 mp4 (Gif to mp4)
  • 将 mp4 转换为 Lottie json (Mp4 to Json)
  • 将您的 Lottie json 上传到 lottiefiles.com 或添加到您的 assets 文件夹
  • 使用 Lottie 包加载您的动画

尝试从 Medium 中查看本教程:“Explore Lottie Animation In Flutter”。

【讨论】:

    【解决方案2】:

    无法使用 Flutter 的 Image 小部件来操作 GIF 播放。但是,您可以尝试使用flutter_gifimage 插件 - 这可以让您更改 GIF 的播放速度并控制屏幕上显示的帧。

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 2011-09-13
      • 2015-01-27
      • 2013-12-29
      • 2019-05-24
      • 2010-10-23
      相关资源
      最近更新 更多