UIGraphicsGetImageFromCurrentImageContext()返回nil

时间:2017-09-07 15:35:23

标签: ios swift uiimage

我有UIImage的扩展名:

extension UIImage {

 func resizeImage(newWidth: CGFloat, newHeight: CGFloat? = nil) -> UIImage {

    let scale = newWidth / self.size.width
    let finalHeight = (newHeight == nil) ? self.size.height * scale : newHeight!

    UIGraphicsBeginImageContextWithOptions(CGSize(width:newWidth, height: finalHeight), false, self.scale)
    self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: finalHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
 }
}

为什么UIGraphicsGetImageFromCurrentImageContext返回nil?它与图像尺寸有关吗?

(lldb)po self.size ▿(3024.0,4032.0)    - 宽度:3024.0    - 身高:4032.0

enter image description here

2 个答案:

答案 0 :(得分:1)

类似于UIGraphicsBeginImageContextWithOptions的实现,以便它尝试为图像缓冲区分配连续的内存区域。该区域确实很大,可以达到50MB。发生的是,“ malloc”调用返回null,并且对UIGraphicsBeginImageContextWithOptions的调用静默失败。 malloc失败的原因可能不同于内存短缺到内存碎片,这是导致此问题重现不一致的原因。

答案 1 :(得分:0)

我也遇到了这个问题。 UIGraphicsGetImageFromCurrentImageContext()第一次返回nil,但是第二次,相同的代码可以获取返回数据。最后我发现,如果视图的子视图的大小为零,则会发生此问题。因此,我建议您检查并删除大小为零的视图子视图。希望为您工作!

相关问题