我在我的项目的xcassets
文件夹中设置了一些.heic
图像以节省空间。然而,我无法通过UIImage(named:)
构造函数加载它们。每次都返回nil
,因此我只能通过指定URL来加载它们。您有任何想法吗?
imageView.image = UIImage(named: "stone") // This returns nil.
如果我将它们作为文件添加到项目中,并通过我创建的方法访问它们,或使用像SDWebImage这样的库,一切都很好,但我认为我正在失去应用程序瘦身的优势,因为这些图像被托管为文件,所以例如,iPhone 7将同时具有2x
和3x
分辨率,而只需要2x
。
extension UIImage {
convenience init?(heicName: String, useScale: Bool = false) {
guard let resourcePath = Bundle.main.path(forResource: heicName.fileName(fileExtension: .heic, useScale: useScale), ofType: nil) else {
return nil
}
let url = URL(fileURLWithPath: resourcePath) as CFURL
guard let source = CGImageSourceCreateWithURL(url, nil),
let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {
return nil
}
self.init(cgImage: image)
}
}
所以我的问题是,有人能向我解释如何将HEIC用作存储在图像资产文件夹中的图像,并使其与应用程序瘦身兼容(只获取所需资源,即2x、3x)的过程吗?
更新: 更多研究后,我意识到当我只在图片视图上设置图像名称时,图像是从IB加载的。您知道这是如何内部工作的吗? IB使用哪个构造函数将UIImage设置为UIImageView?
更新2: 我已向Apple提交了一个雷达: Radar