Swift UIGraphicsGetImageFromCurrentImageContext не может освободить память

Swift Code

Когда мы получаем скриншот UIView, мы обычно используем этот код:

UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Проблема

drawViewHierarchyInRect && UIGraphicsGetImageFromCurrentImageContext будет генерировать изображение в текущем Контексте, но память будет не выпущена при вызове UIGraphicsEndImageContext.

Использование памяти продолжает увеличиваться, пока приложение не сработает.

Несмотря на то, что слово UIGraphicsEndImageContext будет автоматически вызывать CGContextRelease ", оно не работает.

Как я могу освободить используемую память drawViewHierarchyInRect или UIGraphicsGetImageFromCurrentImageContext

Или?

В любом случае создается скриншот без drawViewHierarchyInRect?

Уже пробовал

1 Автоматический выпуск: не работает

var image:UIImage?
autoreleasepool{
    UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
    drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}
image = nil

2 UnsafeMutablePointer: не работает

var image:UnsafeMutablePointer<UIImage> = UnsafeMutablePointer.alloc(1)

autoreleasepool{
   UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
   drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
   image.initialize(UIGraphicsGetImageFromCurrentImageContext())
   UIGraphicsEndImageContext()
}
image.destroy()
image.delloc(1)

Ответы

Ответ 1

Я решил эту проблему, поставив операции с изображениями в другую очередь!

private func processImage(image: UIImage, size: CGSize, completion: (image: UIImage) -> Void) {
    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) {
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        image.drawInRect(CGRect(origin: CGPoint.zero, size: size))
        let tempImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        completion(image: tempImage)
    }
}

Ответ 2

private extension UIImage
{
func resized() -> UIImage {
let height: CGFloat = 800.0
let ratio = self.size.width / self.size.height
let width = height * ratio

let newSize = CGSize(width: width, height: height)
let newRectangle = CGRect(x: 0, y: 0, width: width, height: height)

UIGraphicsBeginImageContext(newSize)
self.draw(in: newRectangle)

let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return resizedImage!
} 
}