在 iOS 中创建带有 URL 的 UIImage [英] Create a UIImage with a URL in iOS

查看:12
本文介绍了在 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: 以通过网络获取图像作为原始数据,然后使用 +imageWithData:UIImage 上的 code> 类方法,用于将数据转换为图像.

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天全站免登陆