在iOS中使用URL创建UIImage [英] Create a UIImage with a URL in iOS

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

问题描述

要使用图像文件创建UiImage,请使用以下代码:

To create an UiImage with a image file, I use the code as below:

UIImage *aImage = [[UIImage imageNamed:@"demo.jpg"]autorelease];

如果我想创建URL为 http://example.com/demo.jpg,该怎么做?

If I want to create an UiImage with the URL http://example.com/demo.jpg, how to do that?

谢谢

更新

推荐答案

这是一个三步过程.首先,您将创建一个NSURL对象,以保存我们尝试访问的URL.我们会将这个URL提供给NSData类方法,+dataWithContentsOfURL:以便通过网络获取原始图像数据,然后在UIImage上使用+imageWithData:类方法将数据转换为图像.

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 *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

请注意,+dataWithContentsOfURL:执行同步网络请求.如果在主线程上运行它,它将阻塞UI,直到从网络接收到图像数据为止.最佳实践是在后台线程上运行任何网络代码.如果您的目标是OS 4.0+,则可以执行以下操作...

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...

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];
    });
});

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

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