gpt4 book ai didi

xcode - 使用 contentsOfFile 的 UIImage

转载 作者:IT王子 更新时间:2023-10-29 05:25:10 25 4
gpt4 key购买 nike

我正在使用

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

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

If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.

我的 View 允许在选择图像之前循环浏览图像,因此内存占用会随着我循环浏览而增加,即使我从该 View 导航回来也不会下降。

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

我试过使用:

NSBundle.mainBundle().resourcePath

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

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

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

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

最佳答案

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

swift 5:

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

老 swift :

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

关于xcode - 使用 contentsOfFile 的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29376520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com