開發(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)存的變化。
- 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
- UIImage.init(named:"" )
如果用此方法 即使執(zhí)行動(dòng)畫結(jié)束的方法內(nèi)存也不會(huì)被釋放。
demo