16

我在用

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

UIIMageView. 我的应用程序中的图像位于images.xcassets. 问题在于,这个特定init的缓存图像以按照Apple 官方文档重用:

如果您有一个只显示一次的图像文件并希望确保它不会被添加到系统的缓存中,您应该使用imageWithContentsOfFile:创建您的图像。这将使您的一次性图像远离系统图像缓存,从而潜在地改善您的应用程序的内存使用特性。

我的视图允许在选择图像之前循环浏览图像,因此当我循环浏览时内存占用量会继续增加,即使我从该视图返回时也不会下降。

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

我试过使用:

NSBundle.mainBundle().resourcePath

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

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

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

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

4

3 回答 3

39

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

斯威夫特 5:

let bundlePath = Bundle.main.path(forResource: "imageName", ofType: "jpg")
let image = UIImage(contentsOfFile: bundlePath!)

老斯威夫特:

let bundlePath = NSBundle.mainBundle().pathForResource("imageName", ofType: "jpg") 
let image = UIImage(contentsOfFile: bundlePath!) 
于 2015-04-01T18:36:12.047 回答
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)
于 2018-12-20T06:24:34.073 回答
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!)
于 2018-02-07T11:06:02.550 回答