ios – swift UIGraphicsGetImageFromCurrentImageContext无法释放内存

SWIFT代码

当我们得到一个UIView的屏幕截图时,我们通常使用这个代码

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

问题

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

内存使用继续增加,直到应用程序崩溃.

虽然有一个字UIGraphicsEndImageContext会自动调用CGContextRelease“,它不起作用.

如何释放内存drawViewHierarchyInRect或UIGraphicsGetimageFromCurrentimageContext used

要么?

有没有生成屏幕截图没有drawViewHierarchyInRect?

已经尝试过

1 Auto release : not work

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

2 UnsafeMutablePointer : not work

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

autoreleasepool{
   UIGraphicsBeginImageContextWithOptions(frame.size,scale)
   drawViewHierarchyInRect(bounds,afterScreenUpdates: true)
   image.initialize(UIGraphicsGetimageFromCurrentimageContext())
   UIGraphicsEndImageContext()
}
image.destroy()
image.delloc(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)
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...