代码之家  ›  专栏  ›  技术社区  ›  Andrea

Swift 3中路径或文件名的UIImage

  •  4
  • Andrea  · 技术社区  · 8 年前

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

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

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

    有人能提出建议吗?我对iOS编程有点在行。

    func getImgPath(name: String) -> String
    {
        let documentsDirectory = self.getDocumentsDirectory()
        let fullpath = documentsDirectory.appendingPathComponent(name)
        return fullpath.absoluteString
    
    }
    
    4 回复  |  直到 8 年前
        1
  •  13
  •   pkamb santoshIOS    8 年前

    这可能会有所帮助

    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
    }
    
        2
  •  4
  •   user8567812 user8567812    8 年前

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

    UIImage(named: 'yourImageName')
    

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

        3
  •  0
  •   Papershine    8 年前

    您可以获得图像的路径,如下所示:

    let imagePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("image.jpg")
    

    如果这不起作用,请检查文件名是否正确。

        4
  •  0
  •   Austin Michael    8 年前

    我明白,如果你是从互联网下载图像,你需要转换 URL UIImage

        if let url = URL(string: "your url") {
            let data = try? Data(contentsOf: url)
            if let imageData = data {
                if let image = UIImage(data: imageData) {
                    imageView.image = image
                }
            }
        }
    

    如果我理解你的问题是正确的,这将是答案。