UIButton+MOSvga.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // UIButton+MOSvga.m
  3. // MiMoLive
  4. //
  5. // Created by SuperC on 2023/11/24.
  6. //
  7. #import "UIButton+MOSvga.h"
  8. #import "SVGA.h"
  9. #import "YYKit.h"
  10. static SVGAParser *parser;
  11. @implementation UIButton (MOSvga)
  12. - (void)mo_setImageWithUrl:(NSString *)urlString forState:(UIControlState)state placeholder:(UIImage *)placeholderImage loops:(int)loops AndFrame:(CGRect)rectFrame{
  13. //-135只是一个自定义的tag值,避免一些常用的1.2.3.4.5等值。
  14. SVGAPlayer *player = [self viewWithTag:-135-state];
  15. //创建SVGAPlayer
  16. if (player == nil)
  17. {
  18. //跟imageView大小相同
  19. player = [[SVGAPlayer alloc] initWithFrame:self.imageView.bounds];
  20. player.tag = -135-state;
  21. //超出边框的需要被裁剪,否则出现出界的情况
  22. self.imageView.clipsToBounds = YES;
  23. [self.imageView addSubview:player];
  24. }
  25. //每次重新给player的frame赋值,不然刷新时,部分会出现宽高为0的问题
  26. player.frame = rectFrame;
  27. //创建解析对象
  28. parser = [[SVGAParser alloc] init];
  29. //从url中解析
  30. [parser parseWithURL:[NSURL URLWithString:urlString] completionBlock:^(SVGAVideoEntity * _Nullable videoItem)
  31. {
  32. if (videoItem != nil)
  33. {
  34. //把背后的图片设置为空
  35. player.hidden = NO;
  36. //设置动画item
  37. player.videoItem = videoItem;
  38. //设置循环次数
  39. if (loops >0)
  40. {
  41. player.loops = loops;
  42. }
  43. //停止后是否清除动画。默认YES,NO的话会停在最后一帧。
  44. player.clearsAfterStop = NO;
  45. //播放动画
  46. [player startAnimation];
  47. }
  48. } failureBlock:^(NSError * _Nonnull error)
  49. {
  50. MOLogV(@"SVGAParser error : %@",error);
  51. }];
  52. WEAKSELF
  53. [self addObserverBlockForKeyPath:@"buttonType" block:^(id _Nonnull obj, id _Nullable oldVal, id _Nullable newVal)
  54. {
  55. SVGAPlayer *player0 = [weakSelf viewWithTag:(-135-[oldVal integerValue])];
  56. [player0 stopAnimation];
  57. player0.hidden = YES;
  58. SVGAPlayer *player1 = [weakSelf viewWithTag:(-135-[newVal integerValue])];
  59. [player1 startAnimation];
  60. }];
  61. }
  62. - (void)dealloc
  63. {
  64. [self removeObserverBlocksForKeyPath:@"buttonType"];
  65. }
  66. @end