1. 程式人生 > 其它 >UIImageView關鍵幀動畫,監聽動畫結束的回撥

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