gpt4 book ai didi

objective-c - 在 iOS 中创建带有 URL 的 UIImage

转载 作者:IT老高 更新时间:2023-10-28 11:36:39 39 4
gpt4 key购买 nike

要创建带有图像文件的 UiImage,我使用如下代码:

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

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

谢谢

更新

enter image description here

最佳答案

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

NSURL *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

请注意 +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];
});
});

关于objective-c - 在 iOS 中创建带有 URL 的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7694215/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com