Swift 裁剪的 UIImage 占用超过 300 MB 内存

问题描述

我有一个包含 96 个 UIImages (1280 * 720) 的数组,我对每个 UIImage 裁剪了 720 * 720 个并将新图像保存在一个新数组中。

功能后,我的手机内存最多可提升至 400 MB,并且不会被释放。 我已经用 autoreleasepool 试过了,但没有帮助。

是我的裁剪功能有问题还是为什么内存没有释放?

这是我的代码

Image of looping through the image array and save the new cropped image

cropping function

Memory

解决方法

避免使用 UIGraphicsImageBeginWithContext 并使用 UIGraphicsImageRenderer,如下所示。

有关更多详细信息,请参阅来自(17:00 分钟):https://developer.apple.com/videos/play/wwdc2018/416

        let bounds = CGRect(x: 0,y: 0,width:720,height: 720)
        let renderer = UIGraphicsImageRenderer(size: bounds.size)
        let image = renderer.image { context in // Use this Image
            // Drawing Code
            Your_View.drawHierarchy(in: bounds,afterScreenUpdates: true)
        }