iOS多张图片动画(序列帧)造成的内存增加处理

开发中可能会遇到一系列图片组成的动画功能,图片可能会达到几十张甚至上百张,这时我们会用到序列帧的方法把这些图片放到数组中,让imageview的animation动画去执行。如:

  self.imgView?.animationImages = imgArr //数组
  self.imgView?.animationDuration = animateTime//动画时间
  self.imgView?.animationRepeatCount = repeatCount //是否重复
  self.imgView?.startAnimating()

本地加载图片的方式常用的有:

UIImage.init(named:"" )
UIImage.init(contentsOfFile: imagePath ?? "")

这两种方式有什么不同呢?
1) imageNamed:
图片是加载到缓存中的,即使指向他的指针被销毁了,内存中依然会存在。好处是能快速加载该图片,如果这个图片经常被用到建议此方法。
2) imageWithContentsOfFile:
图片是不会缓存的,如果指向他的指针被销毁,内存也会被释放。这个方法适合不经常使用,或者数量多的图片。序列帧的图片非常适合使用这个方法。

现在通过下面这个例子来感受一下使用两种方法内存的变化。

  1. imageWithContentsOfFile方法
 // MARK: ---- 动画
    func startAnimations(_ repeatCount:Int) {
        var stringCount = ""
        var imgArr = [UIImage]()
        var imag:UIImage?

        for index in 15..<107{
            stringCount =  index < 100 ? String(format: "000%d", index) : String(format: "00%d", index)
            let imagePath =    bundlePath.path(forResource: "load_\(stringCount)", ofType: "png")
            imag = UIImage.init(contentsOfFile: imagePath ?? "")
            imgArr.append(imag!)
        }
        self.beginAnimate(imgArr, TimeInterval(MagicView.Cookie_AnimationTime),repeatCount)
    }
    
    
    func beginAnimate(_ imgArr:Array,_ animateTime:TimeInterval,_ repeatCount:Int)  {
        self.imgView?.animationImages = imgArr
        self.imgView?.animationDuration = animateTime
        self.imgView?.animationRepeatCount = repeatCount
        self.imgView?.startAnimating()
    }

这个动画是由90多张图片组成,图片一共有4M左右。
用真机跑的话动画运行起来的时候


image.png

当点击停止动画时执行:

 //动画结束
    func mg_stopAnimation() {
        self.imgView?.stopAnimating()
        self.imgView?.animationImages = nil   //这句话非常重要
    }
image.png
  1. UIImage.init(named:"" )
    如果用此方法 即使执行动画结束的方法内存也不会被释放。
    demo

你可能感兴趣的:(iOS多张图片动画(序列帧)造成的内存增加处理)