Swift代码
当我们得到一个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 = nil2 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)发布于 2016-04-29 16:56:36
我通过将图像操作放到另一个队列中来解决这个问题!
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)
}
}发布于 2017-05-24 21:19:15
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!
}
}https://stackoverflow.com/questions/30993485
复制相似问题