一.可以直接通過UIImageView提供的方法animationDuration進行一組圖片的動畫,具體代碼如下:
dispatch_async(dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT), ^{
for (int i = 0; i < 87; i++) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"Bundle"];
//拼接路徑
filePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"backImage-%d.png", i]];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
[self.dataSour addObject:image];
}
dispatch_async(dispatch_get_main_queue(), ^{
_backView.animationImages = self.dataSour;
_backView.animationDuration = self.dataSour.count / 24;
_backView.animationRepeatCount = 1;
[_backView startAnimating];
[self performSelector:@selector(animationOver) withObject:nil afterDelay:(_backView.animationDuration + 1.1)];
});
});
- (void) animationOver
{
TBLog(@"調用了");
[_backView stopAnimating];
_backView.animationImages = nil;
}
1.大家可以看一下,在這廢話不多說,直接說一下我的思路,加載圖片的時候直接使用的是imageWithContentsOfFile方法,這里好處就不多說,相信大家都懂;
2.在向數組里面加載圖片的時候,我是開一條線程,然后再子線程中進行此操作,原因很簡單,就是因為此操作是耗時操作,如果放在主線程中進行操作,那么就會卡住線程,這里面我說一下我的使用場景:我的這個動畫是放到登錄頁面的,如果我點擊退出登錄時需要重新創建登錄頁,此時正在進行添加圖片到數組的耗時操作卡住主線程,造成的現象就是,點擊“退出登錄”按鈕要等待1-2s中才能有反應,這樣的體驗很差
3.這個方法的最大優點就是操作簡單,缺點就是耗內存,同時不很很準確的去監控動畫的結束時間,這樣一來就沒辦法很準確的在動畫執行完畢后進行相應的操作,所以果斷放棄,我們可以使用方法二進行替換。
二.使用CAKeyframeAnimation進行該動畫的實現
dispatch_async(dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT), ^{
for (int i = 0; i < 87; i++) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"bundle"];
//拼接路徑
filePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"loginbackground_%d.png", i]];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
CGImageRef cgimg = image.CGImage;
[weakObject.dataSour addObject:(__bridge UIImage *)cgimg];
}
dispatch_async(dispatch_get_main_queue(), ^{
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
animation.duration = weakObject.dataSour.count / 24.0;
animation.delegate = weakObject;
animation.values = weakObject.dataSour;
[weakObject.backView.layer addAnimation:animation forKey:nil];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"logo" ofType:@"bundle"];
//拼接路徑
filePath = [filePath stringByAppendingPathComponent:@"loginbackground_83.png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
weakObject.backView.image = image;
});
});
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
TBLog(@"animationDidStop");
[self.dataSour removeAllObjects];
[UIView animateWithDuration:1.0 animations:^{
self.bottomView.alpha = 1.0;
}];
}
方法二的最大的優勢就是可以準確的監控動畫執行結束,這種方法解決我現在最大的痛點。但是它也不是完美的,在消耗內存方面,沒有什么改善,我找了很多資料,但是到目前為止沒有解決這個方法,希望各位大神有什么好的建議都可以進行交流。。。。