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
基础教程推荐
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01