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
要么?
反正有没有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)
我通过将图像操作放在另一个队列中解决了这个问题!
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) } }
根据这篇文章 ,你可能想要将line image = nil
改成@autoreleasepool
块。
我没有尝试过,你可以试试。 祝你好运!
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! } }