最近有个项目要用到UIImageView序列帧的动画,就顺手研究了一下,并对齐进行了后期内存的优化。现在将代码片段和源码弄出来和大家一起分享下。
// 从自己创建的bundle中获取UIImage并加入array中,最后将数组返回
- (NSArray *)initialImageArray {
if (self.imageBundle) {
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int i = 1; i < 24; i++) {
NSString *imageName = [NSString stringWithFormat:@"%03d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName inBundle:self.imageBundle compatibleWithTraitCollection:nil];
[imageArray addObject:image];
}
return imageArray;
}
return nil;
}
// 配置imageview的序列帧动画属性
- (void)configMainImageView {
self.mainImageView.animationImages = [self initialImageArray];// 序列帧动画的uiimage数组
self.mainImageView.animationDuration = 3.f;// 序列帧全部播放完所用时间
self.mainImageView.animationRepeatCount = 1;// 序列帧动画重复次数
[self.mainImageView startAnimating];//开始动画
}
我在项目中自己创建了一个存放拖片的bundle文件,我将bundle里面的图片全部创建为UIImage,并存放的数组中赋值给UIImageView的序列帧数组。然后run我的项目,效果没有问题,但是在查看内存的时候发现如图所示可怕的事情
这样的内存消耗是我所不能接受的,接下来就是对代码性能的优化。查看了一些帖子,我将代码优化成的下面的样子
// 从自己创建的bundle中获取UIImage并加入array中,最后将数组返回
- (NSArray *)initialImageArray {
if (self.imageBundle) {
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
for (int i = 1; i < 24; i++) {
NSString *imageName = [NSString stringWithFormat:@"%03d.jpg", i];
// UIImage *image = [UIImage imageNamed:imageName inBundle:self.imageBundle compatibleWithTraitCollection:nil];
// 性能优化处,直接以文件路径的形式创建image
NSString *imagePath = [NSString stringWithFormat:@"%@/%@", [self.imageBundle bundlePath], imageName];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
[imageArray addObject:image];
}
return imageArray;
}
return nil;
}
// 配置imageview的序列帧动画属性
- (void)configMainImageView {
self.mainImageView.animationImages = [self initialImageArray];// 序列帧动画的uiimage数组
self.mainImageView.animationDuration = 3.f;// 序列帧全部播放完所用时间
self.mainImageView.animationRepeatCount = 1;// 序列帧动画重复次数
[self.mainImageView startAnimating];//开始动画
[self performSelector:@selector(clearAinimationImageMemory) withObject:nil afterDelay:3.f];// 性能优化的重点来了,此处我在执行完序列帧以后我执行了一个清除内存的操作
}
// 清除animationImages所占用内存
- (void)clearAinimationImageMemory {
[self.mainImageView stopAnimating];
self.mainImageView.animationImages = nil;
}
看看如此优化之后的效果是什么样的
看到如此显著的效果甚是欣慰,希望对想要对uiimageview序列帧使用的程序猿们有所帮助。在此附上代码下载链接http://download.csdn.net/detail/zyr124/9301535