2015-06-23 165 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