【问题标题】:Animating UIImageView动画 UIImageView
【发布时间】:2018-06-16 19:30:24
【问题描述】:

当我使用图像序列为 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:) 但问题仍然存在并且内存没有恢复正常。播放动画一次并从内存中删除它的缓存还有哪些其他选项?

【问题讨论】:

    标签: ios swift animation uiimageview


    【解决方案1】:

    您对UIImage(contentsOfFile:) 的使用很好,但是您将图像存储在数组属性而不是语言环境变量中。因此,您的应用会长期保持对所有图像的强引用。

    移动:

    var animationImages = [UIImage]()
    

    viewDidLoad 方法内部,所以它是一个局部变量而不是类属性。

    但即便如此,图像视图仍将所有图像保存在内存中。完成动画后,您需要添加代码以将图像视图的animationImages 设置为nil。如果您想保留最后一张图片,也许您可​​以将其 image 属性设置为最后一张图片。

    【讨论】:

    • 内存仍然增加。
    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 2010-09-30
    • 1970-01-01
    • 2016-10-23
    • 2010-12-27
    • 2012-09-16
    相关资源
    最近更新 更多