我建议你试试
UIImage(contentsOfFile:)
而不是
UIImage(named:)
。在我的快速测试中,发现速度快了一个数量级以上。这在某种程度上是可以理解的,因为它做了很多事情(搜索资产、缓存资产等)。
// slow
@IBAction func didTapNamed(_ sender: Any) {
let start = CFAbsoluteTimeGetCurrent()
imageView.animationImages = (0 ..< 20).map {
UIImage(named: filename(for: $0))!
}
imageView.animationDuration = 1.0
imageView.animationRepeatCount = 1
imageView.startAnimating()
print(CFAbsoluteTimeGetCurrent() - start)
}
// faster
@IBAction func didTapBundle(_ sender: Any) {
let start = CFAbsoluteTimeGetCurrent()
let url = Bundle.main.resourceURL!
imageView.animationImages = (0 ..< 20).map {
UIImage(contentsOfFile: url.appendingPathComponent(filename(for: $0)).path)!
}
imageView.animationDuration = 1.0
imageView.animationRepeatCount = 1
imageView.startAnimating()
print(CFAbsoluteTimeGetCurrent() - start)
}
注意,这假定您在资源目录中有这些文件,您可能需要根据它们在项目中的位置进行相应的修改。还请注意,我避免这样做
Bundle.main.url(forResource:withExtension:)
在循环中,因为即使这样也会对性能产生明显的影响。