我想通过单击按钮来控制 gif 动画,即,如果我按下“单击我”按钮动画开始并再次按下动画应该停止。我正在参考这个问题如何在 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();
}
},
),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
目前,Flutter 支持GIF使用 widget 播放文件Image。
但仍然没有简单的方法来控制(例如暂停和播放)文件GIF。当谈到控制它时,解决方法之一是使用包。Lottie for Flutter可以用来实现此行为。
解决方法:
- 将您的 gif 转换为 mp4 ( Gif 转 mp4 )
- 将 mp4 转换为 Lottie json ( Mp4 为 Json )
- 将您的 Lottie json 上传到
lottiefiles.com或添加到您的assets文件夹- 使用 Lottie 包加载你的动画
尝试从 Medium 上查看这个教程:“探索 Flutter 中的 Lottie 动画”。
| 归档时间: |
|
| 查看次数: |
1487 次 |
| 最近记录: |