| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- //
- // UIButton+MOSvga.m
- // MiMoLive
- //
- // Created by SuperC on 2023/11/24.
- //
- #import "UIButton+MOSvga.h"
- #import "SVGA.h"
- #import "YYKit.h"
- static SVGAParser *parser;
- @implementation UIButton (MOSvga)
- - (void)mo_setImageWithUrl:(NSString *)urlString forState:(UIControlState)state placeholder:(UIImage *)placeholderImage loops:(int)loops AndFrame:(CGRect)rectFrame{
- //-135只是一个自定义的tag值,避免一些常用的1.2.3.4.5等值。
- SVGAPlayer *player = [self viewWithTag:-135-state];
-
- //创建SVGAPlayer
- if (player == nil)
- {
- //跟imageView大小相同
- player = [[SVGAPlayer alloc] initWithFrame:self.imageView.bounds];
- player.tag = -135-state;
- //超出边框的需要被裁剪,否则出现出界的情况
- self.imageView.clipsToBounds = YES;
- [self.imageView addSubview:player];
- }
-
- //每次重新给player的frame赋值,不然刷新时,部分会出现宽高为0的问题
-
- player.frame = rectFrame;
-
- //创建解析对象
- parser = [[SVGAParser alloc] init];
- //从url中解析
- [parser parseWithURL:[NSURL URLWithString:urlString] completionBlock:^(SVGAVideoEntity * _Nullable videoItem)
- {
- if (videoItem != nil)
- {
- //把背后的图片设置为空
- player.hidden = NO;
- //设置动画item
- player.videoItem = videoItem;
- //设置循环次数
- if (loops >0)
- {
- player.loops = loops;
- }
- //停止后是否清除动画。默认YES,NO的话会停在最后一帧。
- player.clearsAfterStop = NO;
- //播放动画
- [player startAnimation];
- }
-
- } failureBlock:^(NSError * _Nonnull error)
- {
- MOLogV(@"SVGAParser error : %@",error);
- }];
-
- WEAKSELF
- [self addObserverBlockForKeyPath:@"buttonType" block:^(id _Nonnull obj, id _Nullable oldVal, id _Nullable newVal)
- {
- SVGAPlayer *player0 = [weakSelf viewWithTag:(-135-[oldVal integerValue])];
- [player0 stopAnimation];
- player0.hidden = YES;
-
- SVGAPlayer *player1 = [weakSelf viewWithTag:(-135-[newVal integerValue])];
- [player1 startAnimation];
- }];
- }
- - (void)dealloc
- {
- [self removeObserverBlocksForKeyPath:@"buttonType"];
- }
- @end
|