ImageFromCurrentImageContext无法释放

ImageFromCurrentImageContext无法释放

本文介绍了快速的UIGraphicsGetImageFromCurrentImageContext无法释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获得UIView的屏幕截图时,通常使用以下代码:

When we get a screenshot of a UIView, we use this code usually:

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

问题

drawViewHierarchyInRect&& UIGraphicsGetImageFromCurrentImageContext会在当前上下文中生成图像,但调用UIGraphicsEndImageContext时会释放内存.

Problem

drawViewHierarchyInRect && UIGraphicsGetImageFromCurrentImageContext will generate an image in current Context,but Memory will not released when when called UIGraphicsEndImageContext.

内存使用量持续增加,直到应用程序崩溃为止.

Memory using continues to increase until the app crashes.

尽管有一个词UIGraphicsEndImageContext会自动调用CGContextRelease",但这是行不通的.

Although there is a word UIGraphicsEndImageContext will call CGContextRelease automatically",it doesn't work.

如何释放drawViewHierarchyInRectUIGraphicsGetImageFromCurrentImageContext使用的内存

在没有drawViewHierarchyInRect的情况下是否仍会生成屏幕截图?

Is there anyway generating screenshot without drawViewHierarchyInRect?

var image:UIImage?
autoreleasepool{
    UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
    drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}
image = nil
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)

推荐答案

我通过将图像操作放在另一个队列中解决了这个问题!

I solved this problem by putting image operations in another queue!

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

这篇关于快速的UIGraphicsGetImageFromCurrentImageContext无法释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 08:38