使用contentsOfFile的UIImage [英] UIImage using contentsOfFile

查看:1042
本文介绍了使用contentsOfFile的UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

self.imageView.image = UIImage(名称:foo.png)

UIIMageView 中选择和加载图像。我的应用程序中的图像位于 images.xcassets 下。问题是这个特定的 init 根据 Apple官方文档

to select and load images in an UIIMageView. I have the images in my app under the images.xcassets. The problem is that this particular init caches the image for reuse as per the official Apple documentation:


如果您的图像文件只显示一次并且希望
确保它没有添加到系统的缓存中,那么您应该使用 imageWithContentsOfFile:即可。这将
将您的一次性图像保留在系统图像缓存之外,可能需要
来改善应用程序的内存使用特性。

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.

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

My view allows cycling through images before selecting one, and so the memory footprint goes on increasing as I cycle through and never goes down even when I navigate back from that view.

所以我试图使用 UIIMage(contentsOfFile:文件路径)这不会缓存图片。在这里,我无法以编程方式获取我在 images.xcassets 下存储的图像的路径。

So I am trying to use UIIMage(contentsOfFile: "path to the file") which does not cache the image. Here I am having trouble programatically getting the path of the images which I have stored under images.xcassets.

我尝试过使用:

NSBundle.mainBundle()。resourcePath
$

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

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

without luck. For the first one I get the resourcePath, but on accessing that through the terminal I do not see any image assets under it, and the second one I get nil when I use it. Is there an easy way to to do this?

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

Also looked at several SO questions (like this, this and this) with no luck. Do I have to put my images somewhere else to be able to use the pathForResource()? What is the right way to go about this?

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

It is hard to imagine that no one has encountered this scenario before :) !

推荐答案

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

If you need to use pathForResource() for avoiding image caching, it is not possible to work with images.xcassets. In that case you need to create group in XCode, and add image there (be sure, that image is copied to Copy Bundle Resources). Afterwards just write:

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

这篇关于使用contentsOfFile的UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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