CCGIF.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { GIFCache } from "./GIF";
  2. const { ccclass, property } = cc._decorator;
  3. @ccclass
  4. export default class CCGIF extends cc.Component {
  5. delays = [];
  6. sp: cc.Sprite;
  7. frames: cc.SpriteFrame[] = [];
  8. @property(cc.String)
  9. path: string = '';
  10. start() {
  11. this.sp = this.node.addComponent(cc.Sprite);
  12. this.node.active = false;
  13. }
  14. async preload() {
  15. GIFCache.getInstance();
  16. return new Promise((rs, rj) => {
  17. cc.loader.loadRes(this.path, (err, data) => {
  18. // console.log(err, data);
  19. if (err) {
  20. rj(err);
  21. return;
  22. }
  23. let size = data._nativeAsset.spriteFrames[0]._originalSize;
  24. this.node.setContentSize(size);
  25. this.delays = data._nativeAsset.delays.map(v => v / 1e2);
  26. this.frames = data._nativeAsset.spriteFrames;
  27. rs();
  28. })
  29. })
  30. }
  31. frameIdx = 0;
  32. play(loop = false, playNext = false) {
  33. if (!playNext) {
  34. this.stop();
  35. }
  36. if (this.frames.length) {
  37. if (this.frameIdx >= this.frames.length) {
  38. this.frameIdx = 0;
  39. if (!loop) {
  40. this.node.active = false;
  41. return;
  42. }
  43. }
  44. this.node.active = true;
  45. this.sp.spriteFrame = this.frames[this.frameIdx];
  46. this.scheduleOnce(() => {
  47. this.play(loop, true);
  48. }, this.delays[this.frameIdx]);
  49. this.frameIdx++;
  50. }
  51. }
  52. stop() {
  53. this.frameIdx = 0;
  54. this.unscheduleAllCallbacks();
  55. this.node.active = false;
  56. }
  57. }