iOS多張圖片動(dòng)畫(序列幀)造成的內(nèi)存增加處理

開發(fā)中可能會(huì)遇到一系列圖片組成的動(dòng)畫功能,圖片可能會(huì)達(dá)到幾十張甚至上百?gòu)垼@時(shí)我們會(huì)用到序列幀的方法把這些圖片放到數(shù)組中,讓imageview的animation動(dòng)畫去執(zhí)行。如:

  self.imgView?.animationImages = imgArr //數(shù)組
  self.imgView?.animationDuration = animateTime//動(dòng)畫時(shí)間
  self.imgView?.animationRepeatCount = repeatCount //是否重復(fù)
  self.imgView?.startAnimating()

本地加載圖片的方式常用的有:

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

這兩種方式有什么不同呢?
1) imageNamed:
圖片是加載到緩存中的,即使指向他的指針被銷毀了,內(nèi)存中依然會(huì)存在。好處是能快速加載該圖片,如果這個(gè)圖片經(jīng)常被用到建議此方法。
2) imageWithContentsOfFile:
圖片是不會(huì)緩存的,如果指向他的指針被銷毀,內(nèi)存也會(huì)被釋放。這個(gè)方法適合不經(jīng)常使用,或者數(shù)量多的圖片。序列幀的圖片非常適合使用這個(gè)方法。

現(xiàn)在通過下面這個(gè)例子來感受一下使用兩種方法內(nèi)存的變化。

  1. imageWithContentsOfFile方法
 // MARK: ---- 動(dòng)畫
    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<UIImage>,_ animateTime:TimeInterval,_ repeatCount:Int)  {
        self.imgView?.animationImages = imgArr
        self.imgView?.animationDuration = animateTime
        self.imgView?.animationRepeatCount = repeatCount
        self.imgView?.startAnimating()
    }

這個(gè)動(dòng)畫是由90多張圖片組成,圖片一共有4M左右。
用真機(jī)跑的話動(dòng)畫運(yùn)行起來的時(shí)候


image.png

當(dāng)點(diǎn)擊停止動(dòng)畫時(shí)執(zhí)行:

 //動(dòng)畫結(jié)束
    func mg_stopAnimation() {
        self.imgView?.stopAnimating()
        self.imgView?.animationImages = nil   //這句話非常重要
    }
image.png
  1. UIImage.init(named:"" )
    如果用此方法 即使執(zhí)行動(dòng)畫結(jié)束的方法內(nèi)存也不會(huì)被釋放。
    demo
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容