微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决当使用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

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。