当我们获取一个UIView的截图时,我们通常会使用这段代码:
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
drawViewHierarchyInRect && UIGraphicsGetImageFromCurrentImageContext 将在当前 Context 中生成图像,但调用 UIGraphicsEndImageContext 时内存将不会释放>.
内存使用持续增加,直到应用崩溃。
虽然有一句话UIGraphicsEndImageContext会自动调用CGContextRelease”,但它不起作用。
如何释放内存 drawViewHierarchyInRect 或 UIGraphicsGetImageFromCurrentImageContext 使用
有没有不用drawViewHierarchyInRect生成截图的方法?
1 Auto release : not work
var image:UIImage?
autoreleasepool{
UIGraphicsBeginImageContextWithOptions(frame.size, false, 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, false, 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)
}
}
关于ios - swift UIGraphicsGetImageFromCurrentImageContext 无法释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30993485/