当使用UIImagenamed:“”和Bundle.main.pathforResource :)合成图像时,为什么性能有很大不同?

问题描述

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

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,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

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

我的难题是这两种方法在图像合并之前将b的两个图像加载到内存中。但是为什么图像合成过程中会有如此不同?

这样的代码

enter image description here

解决方法

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