Create a UIImage with a URL in iOS(在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 iOS 中创建带有 URL 的 UIImage


- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01