Swift 3 中来自路径或文件名的 UIImage

And*_*rea 3 xcode uiimage ios swift

我的应用程序的文档目录中有一堆图像。我想在我认为的 UIImage 中加载其中一个。这就是我所做的:

myImage.image = UIImage(named: "image.jpg") // the file exist but this returns nil
Run Code Online (Sandbox Code Playgroud)

我还尝试使用以下方法初始化图像:

myImage.image = UIImage(contentsOfFile: imagePath) //this also doesn't work but the path i got starts (at least in the sim) with file://
Run Code Online (Sandbox Code Playgroud)

任何人都可以提出建议吗?我是 iOS 编程的菜鸟。

谢谢

编辑: imagePath 来自:

func getImgPath(name: String) -> String
{
    let documentsDirectory = self.getDocumentsDirectory()
    let fullpath = documentsDirectory.appendingPathComponent(name)
    return fullpath.absoluteString

}
Run Code Online (Sandbox Code Playgroud)

Mau*_*ani 12

这可能有帮助

let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths             = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath        = paths.first
{
   let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("name.png")
   let image    = UIImage(contentsOfFile: imageURL.path)
   // Do whatever you want with the image
}
Run Code Online (Sandbox Code Playgroud)

  • 很高兴它帮助了你。祝你好运。 (2认同)

小智 5

尝试在 下添加您的图像Assets.xcassets。然后您将可以通过以下方式引用您的图像:

UIImage(named: 'yourImageName')
Run Code Online (Sandbox Code Playgroud)

您可以方便地添加具有各种尺寸设置的图像。