提问者:小点点

如何使用Swift从iOS中的包加载图像


我可以加载图像名称,但不能加载实际图像。 这些图像被存储为pdf格式,所以我可以缩放它们。

我用来读取映像名称的代码如下

let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("FlatIcon.bundle")

do {
    let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey, URLResourceKey.pathKey], options: .skipsHiddenFiles)
    return contents.map { $0.lastPathComponent }
}
catch let error as NSError {
  print(error)
}

我用来加载图像的代码

let bundlePath = Bundle.main.path(forResource: "FlatIcon", ofType: "bundle")!
let bundle = Bundle(path: bundlePath)
let resourcePath = (bundle?.path(forResource: name.components(separatedBy: ".").first, ofType: "pdf"))!
return UIImage(contentsOfFile: resourcePath)

这个问题

无论我怎么尝试,我都不能使用包中的图像

更新

使用

bundle?.path(forResource: "flat.address.book", ofType: "pdf")

它会找到路径,但在尝试加载UIImage时

UIImage(contentsOfFile: resourcePath)

图像将为零


共1个答案

匿名用户

name.components(separatedby:“。”)。first,oftype:“pdf”))

以名称flat.address.book.pdf为例,上面的代码将查找名为flat.pdf的图像

确保名字正确无误

可能的解决方案

  1. 使用文本替换从名称中删除。pdf(将“。pdf”替换为“”)
  2. 使用name.components,删除最后一项并用“。”连接