gpt4 book ai didi

ios - swift UIGraphicsGetImageFromCurrentImageContext 无法释放内存

转载 作者:IT王子 更新时间:2023-10-29 05:14:41 24 4
gpt4 key购买 nike

快速代码

当我们获取一个UIView的截图时,我们通常会使用这段代码:

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

问题

drawViewHierarchyInRect && UIGraphicsGetImageFromCurrentImageContext 将在当前 Context 中生成图像,但调用 UIGraphicsEndImageContext 时内存将不会释放>.

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

虽然有一句话UIGraphicsEndImageContext会自动调用CGContextRelease”,但它不起作用。

如何释放内存 drawViewHierarchyInRectUIGraphicsGetImageFromCurrentImageContext 使用

或者?

有没有不用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com