【问题标题】:When use UIImage(named:"") and Bundle.main.path(forResource:) compositing images, why is the performance very different?当使用 UIImage(named:"") 和 Bundle.main.path(forResource:) 合成图像时,为什么性能会有很大差异?
【发布时间】:2020-08-16 11:57:06
【问题描述】:

我需要将两张图片合二为一,其中一张用作背景。我使用时的方法

let a = UIImage(named: "234")
let b = UIImage(named: "720")

let aRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let bRect = CGRect(x: 0, y: 0, width: backgroundImg.size.width, height: backgroundImg.size.height)

  ...
  let render = UIGraphicsImageRenderer(bounds: bRect)
  let result = render.image { renderContext in
      backgroundImg.draw(in: bRect)
      image.draw(in: aRect)
  }
  return result

花了 2 毫秒。

但是当我使用时

let aPath = Bundle.main.path(forResource: "234@3x", ofType: "png")
let bPath = Bundle.main.path(forResource: "720@3x", ofType: "png")

let a = UIImage(contentsOfFile: aPath!)
let b = UIImage(contentsOfFile: bPath!)

  ...
  let render = UIGraphicsImageRenderer(bounds: bRect)
  let result = render.image { renderContext in
      backgroundImg.draw(in: bRect)
      image.draw(in: aRect)
  }
  return result

花了20ms,是什么导致时间增加了10倍?

我的困惑是,这两种方法都在图像组合之前将 a b 的两个图像加载到内存中。但是为什么图像合并的过程会有这样的差异呢?

这样的代码:

enter image description here

【问题讨论】:

    标签: ios swift uikit core-graphics


    【解决方案1】:

    不是图像合成需要更长的时间。这是文件加载。在第一个代码中,图像缓存在内存中,因此在第一次加载之后它们需要零时间。在第二个代码中,图像没有缓存,所以每次都必须从磁盘读取,速度很慢。

    【讨论】:

    • 感谢您的回复。但是您可能误解了我的代码。我的代码在两个图像开始合成之前将图像记录到内存中。我认为这两种方法的图像在执行组合方法时都在内存中。在上面的问题中,我添加了一张图片。您可以点击查看。
    猜你喜欢
    • 2012-03-29
    • 2019-06-30
    • 2017-05-29
    • 2015-06-04
    • 2016-10-14
    • 1970-01-01
    • 2018-11-13
    • 2010-12-24
    • 2014-08-31
    相关资源
    最近更新 更多