UIImageView 序列帧动画及内存优化详解

最近有个项目要用到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

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值