如何在 Swift 中从图像数组中释放图像

2023-12-19

是否有一个“核选项”可以从图像阵列中释放图像?我想播放第一个动画1 (ImageSet1),然后在完成块中删除该动画,然后加载并播放第二个动画2 (ImageSet2),依此类推:清洗、冲洗、重复 - 你明白了:)

首先,我定义 ViewController 的实例变量:

var animation1: [UIImage] = []
var animation2: [UIImage] = []
var animation3: [UIImage] = []

然后我为每个动画创建一个动画数组:

func createImageArray(total: Int, imagePrefix: String) -> [UIImage]{
    var imageArray: [UIImage] = []
    for imageCount in 0..<total {
    let imageName = "\(imagePrefix)-\(imageCount).png"
    let image = UIImage(named: imageName)!
    imageArray.append(image)
    }
    return imageArray
    }

然后我设置动画值:

func animate(imageView: UIImageView, images: [UIImage]){
    imageView.animationImages = images
    imageView.animationDuration = 1.5
    imageView.animationRepeatCount = 1
    imageView.startAnimating() }

    animation1 = createImageArray(total: 28, imagePrefix: "ImageSet1")
    animation2 = createImageArray(total: 53, imagePrefix: "ImageSet2")
    animation3 = createImageArray(total: 25, imagePrefix: "ImageSet3")

最后调用 animate 函数

func showAnimation() {
    UIView.animate(withDuration: 1, animations: {
        animate(imageView: self.animationView, images: self.animation1)

        }, completion: { (true) in

        // Release the Images from the Array

        })
    }

我想从完成块中的图像数组中释放图像以降低内存占用量,但我似乎无法使其工作,我已尝试了下面的所有四个示例,但对内存占用量没有影响:

func showAnimation() { 
UIView.animate(withDuration: 1, animations: { 
animate(imageView: self.animationView, images: self.animation1) 

}, completion: { (true) in 

self.animation1 = [] // is this correct?
self.animationView.image = nil // also doesn't work
self.animationView.removeFromSuperview() // also doesn't work
self.animation1 = nil // also doesn't work

}) 
}

在完成块之后,我将animation1数组设置为等于[],它确实删除了动画(您再也看不到它了),但内存占用保持完全相同(我也尝试了其他三个选项) 。

通过上述操作,每次我添加下一个动画时,内存占用都会“增加”,最终导致操作系统终止应用程序

即使您更改 ViewController,数组仍将图像保存在内存中

谢谢你的帮助 :)


UIImage(named: ) 将始终将图像保存在内存堆栈中,除非需要更多内存和足够的时间来释放。

为了从内存中释放图像,您应该使用其他构造函数: UIImage(contentsOfFile: ) 并将图像保存在文件夹中而不是资源管理器中。也许数据也能起作用,但我不确定。

临时/大型资源会消耗堆,您应该使用“临时保存”方法(例如contentsOfFile)将其从内存中清除。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Swift 中从图像数组中释放图像 的相关文章

随机推荐