YYAnimatedImageView使用心得 监听动图播放完毕

YYAnimatedImageView播放gif、apng(动态png)如何监听播放完毕

// animatedIV就是YYAnimatedImageView
[self.animatedIV addObserver:self forKeyPath:@"currentAnimatedImageIndex" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];

NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"动效图片名" ofType:@"gif"]];

YYImage *img = [YYImage imageWithData:data];

// animatedImgCount记录gif动图内图片的数量
if ([img respondsToSelector:@selector(animatedImageFrameCount)]) {
    self.animatedImgCount = [img animatedImageFrameCount];
}
self.animatedIV.image = img;


// KVO监听回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"currentAnimatedImageIndex"]) {
        if ([change[NSKeyValueChangeNewKey] respondsToSelector:@selector(integerValue)]) {
            NSInteger currentAnimatedImageIndex = [change[NSKeyValueChangeNewKey] integerValue];
            if (self.animatedImgCount > 0) {
                if (currentAnimatedImageIndex == self.animatedImgCount - 1) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        // 动画结束
                        [self endAnimated];
                    });
                }
            }
            else {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self endAnimated];
                });
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/allanGold/article/details/111646051