简体   繁体   English

动画UIImageView

[英]Animating UIImageView

When I animate my imageView with image sequence memory usage increases a lot and doesn't come back to normal after animation finishes. 当我用图像序列对imageView进行动画处理时,内存使用量会增加很多,并且在动画结束后不会恢复正常。 Here's my code 这是我的代码

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
}()

I was googling the whole day and I found out that this happens because animated images are cached into device's memory and I should use UIImage(contentsOfFile:) instead of UIImage(named:) but the problem still persists and memory doesn't come back to normal. 我整天都在搜索,发现发生这种情况是因为动画图像已缓存到设备的内存中,因此我应该使用UIImage(contentsOfFile :)而不是UIImage(named :),但问题仍然存在,并且内存无法恢复正常。 What are some other options to play animation once and the remove it's cache from memory? 播放动画一次并从内存中删除其缓存还有哪些其他选择?

Your use of UIImage(contentsOfFile:) is good but you store the images in an array property instead of a locale variable. 您对UIImage(contentsOfFile:)的使用很好,但是您将图像存储在数组属性中,而不是语言环境变量中。 So your app keeps a longterm strong reference to all of the images. 因此,您的应用对所有图像都有长期的强大参考。

Move: 移动:

var animationImages = [UIImage]()

to inside the viewDidLoad method so it is a local variable instead of a class property. 放在viewDidLoad方法内部,因此它是一个局部变量而不是类属性。

But even then, the image view is keeping all of the images in memory. 但是即使那样,图像视图仍将所有图像保留在内存中。 You will need to add code to set the image view's animationImages to nil when it is done animating. 完成动画animationImages ,您需要添加代码以将图像视图的animationImagesnil Perhaps you could set its image property to just the last image if you want to keep that in view. 如果您希望将其image属性保持在最后,可以将其image属性设置为仅最后一个图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM