【问题标题】:UIGraphicsGetImageFromCurrentImageContext() returns nilUIGraphicsGetImageFromCurrentImageContext() 返回 nil
【发布时间】:2017-09-07 15:35:22
【问题描述】:

我有这个 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

【问题讨论】:

  • "为什么 UIGraphicsEndImageContext 返回 nil?是和图片大小有关吗?"好问题。你为什么不回答呢?试试小图片看看吧!
  • 也可以调用UIGraphicsGetCurrentContext,查看上下文本身是否为nil
  • 我正在调用 UIGraphicsGetCurrentContext 并且它返回 nil...
  • 好吧,那就这样吧。
  • 尺寸为 3 的 3024 x 4032(三倍分辨率设备)将具有超过 3600 万像素。这些数字是不是让你有点害怕?

标签: ios swift uiimage


【解决方案1】:

看起来 UIGraphicsBeginImageContextWithOptions 的实现是为了尝试为图像缓冲区分配连续的内存区域。该区域非常大,可以大到 50MB。发生的情况是“malloc”调用返回 null,并且对 UIGraphicsBeginImageContextWithOptions 的调用以静默方式失败。 malloc失败的原因可能是内存不足,也可能是内存碎片,这就是这个问题的再现不一致的原因。

【讨论】:

    【解决方案2】:

    我也遇到了这个问题。第一次UIGraphicsGetImageFromCurrentImageContext()返回nil,但是同样的代码,第二次可以得到返回数据。最后我发现,如果视图的子视图大小为零,就会出现这个问题。所以我建议你检查并删除大小为零的视图子视图。我希望这对你有用!

    【讨论】:

    • 你的回答很有帮助...!
    猜你喜欢
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2019-06-20
    • 2017-12-16
    • 2014-09-27
    • 2017-06-11
    相关资源
    最近更新 更多