iPhone:如何从 url 获取 UIImage?
如何下载图像并将其转换为 UIImage?
How do you download an image and turn it into a UIImage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何下载图像并将其转换为 UIImage?
How do you download an image and turn it into a UIImage?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(7)
但是,这不是异步的。
However, this isn't asynchronous.
您应该记住,使用您在自己的答案中提供的示例代码加载图像数据将阻塞主线程,直到下载完成。这是可用性禁忌。您的应用程序的用户会认为您的应用程序没有响应。如果你想下载图像,更喜欢 NSURLConnection 在它自己的线程中异步下载它。
阅读有关使用 NSURLConnection 进行异步下载的 Apple 文档。< /a>
下载完成后,您可以从数据对象实例化您的 UIImage:
其中
requestData
和image
是包含类的实例变量,image
是保留的属性。请务必在类的dealloc
例程中释放image
,例如使用self.image=nil;
。You should keep in mind that loading the image data with the sample code you've provided in your own answer will block the main thread until the download has completed. This is a useability no-no. The users of your app will think your app is unresponsive. If you want to download an image, prefer NSURLConnection to download it asynchronously in its own thread.
Read the Apple documentation about async downloads with NSURLConnection.
When your download completes, you can then instantiate your UIImage from the data object:
Where
requestData
andimage
are instance variables of your containing class, andimage
is a retained property. Be sure to releaseimage
in thedealloc
routine of the class, e.g. usingself.image=nil;
.确实,异步加载是必须的,但如果您只需要一个简单的解决方案,也可以通过后台调用来实现。
It is true that Asynchronous loading is a must, but you can also achieve that with a background call if you just need a simple solution.
您可以从 URL 加载
UIImageView
中的图像,而无需阻塞 UI 线程,只需使用dispatch_async
:第一个
dispatch_async
用于加载来自后台 URL 的图像(不阻塞 UI)。第二个dispatch_async
用于实际注入刚刚加载到UIImageView
中的图像。请注意,第二个dispatch_async
设计为在主线程(UI 线程)上工作,即用于更新 UI 的线程。You can load an image in a
UIImageView
from a URL without blocking the UI thread simply using thedispatch_async
:The first
dispatch_async
is used to load the image from the URL in background (without blocking the UI). The seconddispatch_async
is used to actually inject the image just loaded in theUIImageView
. Please, note that the seconddispatch_async
is designed to work on the main thread (the UI thread) that is, indeed, the thread used to update the UI.这里有一个使用块的非常好的例子: http://ios-blog.co.uk/iphone-development-tutorials/uiimage-from-url-%E2%80%93-simplified-using-blocks/
There is a really good example here using blocks: http://ios-blog.co.uk/iphone-development-tutorials/uiimage-from-url-%E2%80%93-simplified-using-blocks/
根据@philfreo的回答,我使用 BrightFutures 快速创建了一个 NSURL 扩展(对于异步回调:
这让我可以这样做:
更新
一个简单的同步扩展可能如下所示:
Based on @philfreo's answer I created a NSURL Extension in swift using BrightFutures (for the asynchronous callback:
This then lets me do:
Update
A simple synchronous extension could look like this:
这就是 @philfreo 的答案在 swift 中的样子:
这在操场上有效:
This is what @philfreo's answer looks like in swift:
This works in a playground: