play_assets_image_view.dart 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // 帧动画Image
  2. import 'package:flutter/material.dart';
  3. class PlayAssetsImageListWidget extends StatefulWidget {
  4. final List<String> assetList;
  5. final double width;
  6. final double height;
  7. final int interval ;
  8. final bool isStop;
  9. const PlayAssetsImageListWidget(
  10. {Key? key,
  11. required this.assetList,
  12. required this.width,
  13. required this.height,
  14. required this.isStop,
  15. required this.interval})
  16. : super(key: key);
  17. @override
  18. State<StatefulWidget> createState() {
  19. return VoiceAnimationImageState();
  20. }
  21. }
  22. class VoiceAnimationImageState extends State<PlayAssetsImageListWidget>
  23. with SingleTickerProviderStateMixin {
  24. // 动画控制
  25. Animation<double>? _animation;
  26. AnimationController? _controller;
  27. @override
  28. void initState() {
  29. super.initState();
  30. final int imageCount = widget.assetList.length;
  31. final int maxTime = widget.interval * imageCount;
  32. // 启动动画controller
  33. _controller = AnimationController(
  34. duration: Duration(milliseconds: maxTime), vsync: this);
  35. _controller?.addStatusListener((AnimationStatus status) {
  36. if (status == AnimationStatus.completed) {
  37. _controller?.forward(from: 0.0); // 完成后重新开始
  38. }
  39. });
  40. _animation = Tween<double>(begin: 0, end: imageCount.toDouble())
  41. .animate(_controller!)
  42. ..addListener(() {
  43. setState(() {});
  44. });
  45. }
  46. @override
  47. void dispose() {
  48. _controller?.dispose();
  49. super.dispose();
  50. }
  51. @override
  52. Widget build(BuildContext context) {
  53. if (widget.isStop) {
  54. _controller?.stop();
  55. } else {
  56. _controller?.forward();
  57. }
  58. int ix = _animation?.value.floor() ?? 0 % widget.assetList.length;
  59. List<Widget> images = [];
  60. // 把所有图片都加载进内容,否则每一帧加载时会卡顿
  61. for (int i = 0; i < widget.assetList.length; ++i) {
  62. if (i != ix) {
  63. images.add(Image.asset(
  64. widget.assetList[i],
  65. width: 0,
  66. height: 0,
  67. ));
  68. }
  69. }
  70. images.add(Image.asset(
  71. widget.assetList[ix],
  72. width: widget.width,
  73. height: widget.height,
  74. ));
  75. return Stack(alignment: AlignmentDirectional.center, children: images);
  76. }
  77. }