当我使用图像序列为我的 imageView 设置动画时,内存使用量会增加很多,并且在动画完成后不会恢复正常。这是我的代码
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
view.addSubview(animationImage)
animationImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
animationImage.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
animationImage.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.9, constant: 0).isActive = true
animationImage.heightAnchor.constraint(equalToConstant: 400).isActive = true
var i = 0
while i < 15 {
let path = Bundle.main.path(forResource: "findItBaltas\(i)", ofType: "png")
animationImages.append(UIImage(contentsOfFile: path!)!)
i += 1
}
animationImage.animationImages = animationImages
animationImage.animationDuration = 3
animationImage.animationRepeatCount = 1
animationImage.startAnimating()
}
var animationImages = [UIImage]()
let animationImage: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
我整天都在谷歌搜索,我发现发生这种情况是因为动画图像被缓存到设备的内存中,我应该使用 UIImage(contentsOfFile:) 而不是 UIImage(named:) 但问题仍然存在并且内存没有恢复正常。播放一次动画并从内存中删除它的缓存还有哪些其他选项?
最佳答案
您对 UIImage(contentsOfFile:)
的使用很好,但是您将图像存储在数组属性中而不是语言环境变量中。因此,您的应用会长期保持对所有图像的强引用。
移动:
var animationImages = [UIImage]()
到 viewDidLoad
方法内部,因此它是一个局部变量而不是类属性。
但即便如此, ImageView 仍会将所有图像保存在内存中。完成动画后,您需要添加代码以将 ImageView 的 animationImages
设置为 nil
。如果您想让最后一张图片可见,也许您可以将它的 image
属性设置为仅最后一张图片。
关于ios - 动画 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48139807/