【问题标题】:swift UIGraphicsGetImageFromCurrentImageContext can't release memoryswift UIGraphicsGetImageFromCurrentImageContext 无法释放内存
【发布时间】:2015-09-08 16:53:01
【问题描述】:

Swift 代码

当我们得到一个 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 个月后没有答案,我想我遇到了同样的问题。我想您没有找到解决方法或解决方法?
  • 我也遇到了同样的问题,正在寻找解决方案。
  • 过去几周我遇到了同样的问题。有人修了吗?

标签: ios swift uiimage uigraphicscontext


【解决方案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)
    }
}

【讨论】:

    【解决方案2】:
    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!
        } 
    }
    

    【讨论】:

    • 我只是不喜欢代码末尾的 BANG 运算符“return resizedImage!”我怎么把 BANG 拿出来....?
    • 欢迎来到 StackOverflow 并感谢您的帮助。但是请用一些解释性散文来扩充您的纯代码答案,以突出最有趣的部分。
    猜你喜欢
    • 1970-01-01
    • 2013-07-30
    • 2022-01-22
    • 2016-05-08
    • 2023-03-11
    • 2011-05-31
    相关资源
    最近更新 更多