2015-06-23 123 views
15

Swift代码

当我们拿到一个UIView的截图中,我们使用此代码通常是:迅速UIGraphicsGetImageFromCurrentImageContext不能释放内存

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) 
+3

我看你有2个月后没有答案,我想我得到了同样的问题。我不认为你找到了解决方法或解决方法? – Martin

+2

我遇到了同样的问题并寻找解决方案。 – Hope

回答

3

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

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

我只是不喜欢代码末尾的BANG运算符“return resizedImage!”我将如何把BANG带出....? –

+1

欢迎来到StackOverflow并感谢您的帮助。但是请用一些解释散文来增加您的代码唯一答案,以突出最有趣的部分。 – Yunnosch