在 iOS 中创建一个带有 URL 的 UIImage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7694215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a UIImage with a URL in iOS
提问by Charles Yeung
To create an UiImage with a image file, I use the code as below:
要使用图像文件创建 UiImage,我使用如下代码:
UIImage *aImage = [[UIImage imageNamed:@"demo.jpg"]autorelease];
If I want to create an UiImage with the URL http://example.com/demo.jpg, how to do that?
如果我想使用 URL http://example.com/demo.jpg创建一个 UiImage ,该怎么做?
Thanks
谢谢
UPDATE
更新
回答by Mark Adams
This is a three step process. First you will create an NSURL
object to hold the URL we are attempting to access. We will supply this URL to the NSData
class method, +dataWithContentsOfURL:
to obtain the image over the network as raw data, then use the +imageWithData:
class method on UIImage
to convert the data into an image.
这是一个三步过程。首先,您将创建一个NSURL
对象来保存我们尝试访问的 URL。我们将这个 URL 提供给NSData
类方法,+dataWithContentsOfURL:
以通过网络获取图像作为原始数据,然后使用+imageWithData:
类方法UIImage
将数据转换为图像。
NSURL *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
Please note that +dataWithContentsOfURL:
executes a synchronous network request. If you run this on the main thread, it will block the UI until the image data is received from the network. Best practice is to run any network code on a background thread. If you're targeting OS 4.0+ you could do something like this...
请注意+dataWithContentsOfURL:
执行同步网络请求。如果在主线程上运行它,它将阻塞 UI,直到从网络接收到图像数据。最佳实践是在后台线程上运行任何网络代码。如果你的目标是 OS 4.0+ 你可以做这样的事情......
NSURL *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
self.imageView.image = [UIImage imageWithData:imageData];
});
});
回答by Dave Kiss
Here's what the same code might look like in Swift:
下面是相同的代码在 Swift 中的样子:
let image_url = NSURL("http://i.imgur.com/3yY2qdu.jpg")
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
let image_data = NSData(contentsOfURL: image_url!)
dispatch_async(dispatch_get_main_queue()) {
// update some UI
let image = UIImage(data: image_data!)
self.imageView.image = image
}
}
回答by vir us
For anyone looking to load image from the web the following library may be helpful:
对于希望从网络加载图像的任何人,以下库可能会有所帮助:
https://github.com/rs/SDWebImage
https://github.com/rs/SDWebImage
It's a UIImageView
category which handles async loading and image caching from url.
这是一个UIImageView
处理来自 url 的异步加载和图像缓存的类别。