使用contentsOfFile的UIImage

时间:2015-03-31 19:07:44

标签: xcode swift ios8 uiimage xcasset

我正在使用

self.imageView.image = UIImage(named: "foo.png")

选择并加载UIIMageView中的图片。我的应用程序中的图像位于images.xcassets下方。问题是这个特定的init根据official Apple documentation缓存图像以供重用:

  

如果您的图像文件只显示一次并希望显示   确保它不会被添加到系统的缓存中,你应该这样做   而是使用 imageWithContentsOfFile:创建您的图像。这将   可能会将您的一次性图像保留在系统图像缓存之外   改善应用的内存使用特性。

我的视图允许在选择图像之前循环显示图像,因此当我循环时内存占用量不断增加,即使从该视图导航回来也不会下降。

所以我尝试使用不缓存图像的UIIMage(contentsOfFile: "path to the file")。在这里,我无法以编程方式获取我在 images.xcassets 下存储的图像的路径。

我尝试过使用:

NSBundle.mainBundle().resourcePath
NSBundle.mainBundle().pathForResource("foo", ofType: "png")

没有运气。对于第一个,我得到了resourcePath,但是在通过终端访问它时,我看不到它下面的任何图像资产,第二个我在使用它时得到nil。有一个简单的方法来做到这一点?

还查看了几个SO问题(例如thisthisthis)但没有运气。我是否必须将我的图像放在其他地方才能使用pathForResource()?什么是正确的方法?

很难想象之前没有人遇到过这种情况:)!

3 个答案:

答案 0 :(得分:32)

如果您需要使用 pathForResource()来避免图像缓存,则无法使用images.xcassets。在这种情况下,您需要在XCode中创建组,并在那里添加图像(确保将该图像复制到Copy Bundle Resources)。然后写下:

var bundlePath = NSBundle.mainBundle().pathForResource("imageName", ofType: "jpg") 
var image = UIImage(contentsOfFile: bundlePath!) 

答案 1 :(得分:1)

import Foundation
import UIKit

enum UIImageType: String {
    case PNG = "png"
    case JPG = "jpg"
    case JPEG = "jpeg"
}

extension UIImage {

    convenience init?(contentsOfFile name: String, ofType: UIImageType) {
        guard let bundlePath = Bundle.main.path(forResource: name, ofType: ofType.rawValue) else {
            return nil
        }
        self.init(contentsOfFile: bundlePath)!
    }

}

使用:

let imageView.image = UIImage(contentsOfFile: "Background", ofType: .JPG)

答案 2 :(得分:0)

当您从图像组资源实现图像阵列时,您可以将每个图像(例如b1,b2,b3,b4,b5)加载为

var imageIndex = 0
lazy var imageList = ["b1","b2","b3","b4","b5"]
let imagePath = Bundle.main.path(forResource: imageList[imageIndex], ofType: "jpg")
imageview.image = UIImage(contentsOfFile: imagePath!)