swift UIGraphicsGetImageFromCurrentImageContext无法释放内存

时间:2015-06-23 03:44:02

标签: ios swift uiimage uigraphicscontext

Swift Code

当我们获得UIView的屏幕截图时,我们通常使用此代码:

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

问题

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

内存使用会持续增加,直到应用崩溃。

虽然有一个字UIGraphicsEndImageContext会自动调用CGContextRelease"但它无法正常工作。

如何释放内存drawViewHierarchyInRectUIGraphicsGetImageFromCurrentImageContext使用

或者

无论如何都会生成没有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)

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:-1)

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