frame_animation_view.dart 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'dart:ui' as ui;
  5. import 'package:archive/archive.dart';
  6. import 'package:crypto/crypto.dart';
  7. import 'package:flutter/cupertino.dart';
  8. import 'package:flutter/services.dart';
  9. import 'package:path_provider/path_provider.dart';
  10. class FrameAnimationView extends StatefulWidget {
  11. final String framePath;
  12. final int frameRate;
  13. final FrameAnimationController? controller;
  14. final double? speed;
  15. final double? width;
  16. final double? height;
  17. const FrameAnimationView({super.key,
  18. required this.framePath,
  19. this.frameRate = 25,
  20. this.controller,
  21. this.speed,
  22. this.width,
  23. this.height});
  24. @override
  25. State<StatefulWidget> createState() {
  26. return FrameAnimationViewState();
  27. }
  28. }
  29. class FrameAnimationViewState extends State<FrameAnimationView> {
  30. int _currentFrame = 0;
  31. Timer? _timer;
  32. List<File> imageFiles = [];
  33. List<ui.Image> images = [];
  34. @override
  35. void initState() {
  36. super.initState();
  37. widget.controller?.bindState(this);
  38. loadFrameFromAssets()
  39. .then((_) => initializeImageFiles())
  40. .then((_) => precacheImageFiles())
  41. .then((_) =>
  42. widget.controller == null || widget.controller!.autoPlay
  43. ? startAnimation()
  44. : null)
  45. .catchError((error) => debugPrint('FrameAnimationView error: $error'));
  46. }
  47. @override
  48. void dispose() {
  49. super.dispose();
  50. _timer?.cancel();
  51. imageFiles.clear();
  52. for (var image in images) {
  53. image.dispose();
  54. }
  55. images.clear();
  56. }
  57. @override
  58. Widget build(BuildContext context) {
  59. if (images.isEmpty) {
  60. return SizedBox(width: widget.width, height: widget.height);
  61. }
  62. return RawImage(
  63. image: images[_currentFrame],
  64. width: widget.width,
  65. height: widget.height,
  66. );
  67. }
  68. Future<void> loadFrameFromAssets() {
  69. if (widget.framePath.isEmpty) {
  70. throw Exception('framePath is null or empty');
  71. }
  72. if (widget.framePath.endsWith('.zip')) {
  73. return unZipToCache();
  74. } else {
  75. return copyToCache();
  76. }
  77. }
  78. Future<void> unZipToCache() async {
  79. // Load the zip file from assets
  80. final ByteData data = await rootBundle.load(widget.framePath);
  81. final List<int> bytes = data.buffer.asUint8List();
  82. // Decode the zip file
  83. final Archive archive = ZipDecoder().decodeBytes(bytes);
  84. // Create a cache directory
  85. final Directory cacheDir = await createCacheDirectory();
  86. // if the cache directory is not empty and frame images count is equal to the zip file's files count
  87. if (cacheDir
  88. .listSync()
  89. .isNotEmpty &&
  90. cacheDir
  91. .listSync()
  92. .length == archive.length) {
  93. return;
  94. }
  95. // Extract the contents of the zip file
  96. for (final ArchiveFile file in archive) {
  97. final String filename = file.name;
  98. final List<int> fileData = file.content as List<int>;
  99. final File newFile = File('${cacheDir.path}/$filename');
  100. if (newFile.existsSync()) {
  101. newFile.deleteSync();
  102. } else {
  103. newFile.createSync(recursive: true);
  104. }
  105. newFile.writeAsBytesSync(fileData);
  106. }
  107. }
  108. Future<void> copyToCache() async {
  109. // Read AssetManifest.json file
  110. final String manifestContent =
  111. await rootBundle.loadString('AssetManifest.json');
  112. // Parse JSON string into Map
  113. final Map<String, dynamic> manifestMap = json.decode(manifestContent);
  114. // Filter the Map to get file paths that start with folderPath
  115. final List<String> filePaths = manifestMap.keys
  116. .where((String key) => key.startsWith(widget.framePath))
  117. .toList();
  118. // Create a cache directory
  119. final Directory cacheDir = await createCacheDirectory();
  120. // if the cache directory is not empty and frame images count is equal to the zip file's files count
  121. if (cacheDir
  122. .listSync()
  123. .isNotEmpty &&
  124. cacheDir
  125. .listSync()
  126. .length == filePaths.length) {
  127. return;
  128. }
  129. // Copy the files to the cache directory
  130. for (final String path in filePaths) {
  131. final ByteData data = await rootBundle.load(path);
  132. final List<int> bytes = data.buffer.asUint8List();
  133. final File newFile = File('${cacheDir.path}/${path
  134. .split('/')
  135. .last}');
  136. if (newFile.existsSync()) {
  137. newFile.deleteSync();
  138. } else {
  139. newFile.createSync(recursive: true);
  140. }
  141. newFile.writeAsBytesSync(bytes);
  142. imageFiles.add(newFile);
  143. }
  144. }
  145. Future<Directory> createCacheDirectory() async {
  146. // Get the temporary directory
  147. final Directory tempDir = await getTemporaryDirectory();
  148. // Create a new directory within the temporary directory
  149. final Directory cacheDir = Directory('${tempDir.path}/frame_anim_cache');
  150. // Check if the directory exists, if not, create it
  151. if (!await cacheDir.exists()) {
  152. await cacheDir.create(recursive: true);
  153. }
  154. // create unique directory by framePath's md5
  155. final Directory frameDir = Directory(
  156. '${cacheDir.path}/${md5.convert(utf8.encode(widget.framePath))
  157. .toString()}');
  158. // Check if the directory exists, if not, create it
  159. if (!await frameDir.exists()) {
  160. await frameDir.create(recursive: true);
  161. }
  162. return frameDir;
  163. }
  164. startAnimation() {
  165. if (imageFiles.isEmpty) {
  166. return;
  167. }
  168. if (_timer != null && _timer!.isActive) {
  169. return;
  170. }
  171. double speed = widget.speed ?? 1.0;
  172. _timer = Timer.periodic(
  173. Duration(milliseconds: 1000 ~/ (widget.frameRate * speed)), (_) {
  174. setState(() {
  175. int targetFrame = (_currentFrame + 1) % imageFiles.length;
  176. _currentFrame =
  177. targetFrame >= images.length ? images.length - 1 : targetFrame;
  178. });
  179. });
  180. }
  181. initializeImageFiles() async {
  182. final Directory cacheDir = await createCacheDirectory();
  183. imageFiles = cacheDir
  184. .listSync()
  185. .map((file) => File(file.path))
  186. .where((file) =>
  187. file.path.endsWith('.png') ||
  188. file.path.endsWith('.jpg') ||
  189. file.path.endsWith('.jpeg') ||
  190. file.path.endsWith('.webp'))
  191. .toList();
  192. if (imageFiles.isEmpty) {
  193. throw Exception('frame images not found');
  194. }
  195. }
  196. precacheImageFiles() {
  197. Stream<File>.fromIterable(imageFiles).asyncMap((file) async {
  198. final Uint8List bytes = await file.readAsBytes();
  199. final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  200. final ui.FrameInfo frameInfo = await codec.getNextFrame();
  201. return frameInfo.image;
  202. }).listen((image) {
  203. images.add(image);
  204. });
  205. }
  206. }
  207. class FrameAnimationController {
  208. final bool autoPlay;
  209. FrameAnimationViewState? _state;
  210. FrameAnimationController({this.autoPlay = true});
  211. void play() {
  212. _state?.startAnimation();
  213. }
  214. void stop() {
  215. _state?._timer?.cancel();
  216. }
  217. bool get isPlaying => _state?._timer?.isActive ?? false;
  218. void bindState(FrameAnimationViewState state) {
  219. _state = state;
  220. }
  221. }