Swift 3 中来自路径或文件名的 UIImage [英] UIImage from path or filename in Swift 3

查看:22
本文介绍了Swift 3 中来自路径或文件名的 UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a bunch of images in my App's Documents Directory. i want to load one of them in an UIImage that i have in my view. this is what i do:

myImage.image = UIImage(named: "image.jpg") // the file exist but this returns nil

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

I also tried to init the image using:

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

谁能给点建议?我是 iOS 编程的菜鸟.

Anyone can suggest something? I'm kinda a noob in iOS programming.

谢谢

imagePath 来自:

imagePath comes from:

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

}

推荐答案

这可能会有所帮助

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
}

这篇关于Swift 3 中来自路径或文件名的 UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆