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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM