当我们获得UIView的屏幕截图时,我们通常使用此代码:
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
drawViewHierarchyInRect
&& UIGraphicsGetImageFromCurrentImageContext
会在当前上下文中生成图像,但在调用UIGraphicsEndImageContext
时,内存将不。
内存使用会持续增加,直到应用崩溃。
虽然有一个字UIGraphicsEndImageContext
会自动调用CGContextRelease
"但它无法正常工作。
如何释放内存drawViewHierarchyInRect
或UIGraphicsGetImageFromCurrentImageContext
使用
无论如何都会生成没有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)
答案 0 :(得分:5)
我通过将图像操作放在另一个队列中解决了这个问题!
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 :(得分:-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!
}
}