首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >迅速的UIGraphicsGetImageFromCurrentImageContext不能释放内存

迅速的UIGraphicsGetImageFromCurrentImageContext不能释放内存
EN

Stack Overflow用户
提问于 2015-06-23 03:44:01
回答 2查看 8.8K关注 0票数 19

Swift代码

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

代码语言:javascript
复制
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

问题

drawViewHierarchyInRect && UIGraphicsGetImageFromCurrentImageContext将在当前上下文中生成一个映像,但是当调用UIGraphicsEndImageContext时,内存将不会释放而不是

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

虽然有一个单词UIGraphicsEndImageContext会自动调用CGContextRelease“,但它不起作用。

如何释放使用的内存drawViewHierarchyInRectUIGraphicsGetImageFromCurrentImageContext

或?

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

已试过

1自动发布:不工作

代码语言:javascript
复制
var image:UIImage?
autoreleasepool{
    UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
    drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
    image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}
image = nil

2 UnsafeMutablePointer :不工作

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2016-04-29 16:56:36

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

代码语言:javascript
复制
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)
    }
}
票数 5
EN

Stack Overflow用户

发布于 2017-05-24 21:19:15

代码语言:javascript
复制
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!
    } 
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30993485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档