UIImageView关键帧动画,监听动画结束的回调

@interface DBAnimationView () <CAAnimationDelegate>

@property (strong, nonatomic) NSMutableArray *imageArrM;

@end

@implementation DBAnimationView

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.animationImageView];
    }
    return self;
}

- (void)startAnimation {
    [self.imageArrM removeAllObjects];
    for(NSInteger i = 0; i < 51; i++){
        // 使用imageWithContentsOfFile加载图片,不会导致内存过大,因为该方法不会缓存,帧动画只使用一次的情况下用。
        NSString *imagePath = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"3_00%02ld.jpg", i] ofType:nil];
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        CGImageRef cgImage = image.CGImage;
        [self.imageArrM addObject:(__bridge UIImage * _Nonnull)(cgImage)];
    }
    
    // UIImageView 关键帧动画
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    // 动画结束之后的回调
    animation.delegate = self;
    animation.duration = 2.0;
    animation.repeatCount = 1;
    // 设置animation的唯一标示,这样在delegate回调的时候能够区分开来
    [animation setValue:@"animation1" forKey:@"customType"];
    animation.values = self.imageArrM;
    [self.animationImageView.layer addAnimation:animation forKey:@""];
}

-(void)animationDidStart:(CAAnimation *)anim {
    NSString *keyPathValue = [anim valueForKey:@"customType"];
    if ([keyPathValue isEqualToString:@"animation1"]) {
        NSLog(@"动画开始了。。。。");
        // 动画开始后,设置为最后一张图片,如果在动画结束时再设置,可能会出现图片跳动。
        _animationImageView.image = [UIImage imageNamed:@"3_0050.jpg"];
    }
}
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    NSString *keyPathValue = [anim valueForKey:@"customType"];
    if ([keyPathValue isEqualToString:@"animation1"]) {
        // 释放内存
        _imageArrM = nil;
        // 如果上层需要处理,回调给上层
        if (self.Completion) {
            self.Completion();
        }
    }
}

-(UIImageView *)animationImageView {
    if (!_animationImageView) {
        // 设置初始图片
        _animationImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"3_0000.jpg"]];
        _animationImageView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
        _animationImageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _animationImageView;
}

-(NSMutableArray *)imageArrM {
    if (!_imageArrM) {
        _imageArrM = [NSMutableArray array];
    }
    return _imageArrM;
}

 

posted on 2021-06-25 10:56  大圣ios博客  阅读(879)  评论(0编辑  收藏  举报