IOS加载网络图片的框架(共有4中方法)
框架名为:UIImage+WebCache.h 继承于UIimageView
框架里面加载网络图片的方法共4中:分别为1.普通加载 2.线程NSThread 3.
#import "ViewController.h"
#import "UIImage+WebCache.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
imageArray = [NSMutableArray array];
for(int i = 0;i < 5;i++){
for(int j = 0;j < 6;j++){
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(j*65 +5, i*64 +10, 60, 60)];
imageView.backgroundColor = [UIColor cyanColor];
[self.view addSubview:imageView];
[imageArray addObject:imageView];
}
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(160, 400, 80, 30);
[button setTitle:@"载入" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonAction{
for(UIImageView *imageView in imageArray){
NSString *string = @"http://img3.douban.com/view/photo/photo/public/p2221339563.jpg";
NSURL *url = [NSURL URLWithString:string];
[imageView setImageWithURL:url];
}
}
#import <UIKit/UIKit.h>
@interface UIImageView (WebCache)
- (void)setImageWithURL:(NSURL *)url;
@end
#import "UIImage+WebCache.h"
@implementation UIImageView (WebCache)
- (void)setImageWithURL:(NSURL *)url{
//第一种方法:普通的加载
/*
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self setImage:image];
*/
//第二种方法:线程
//NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage:) object:url];
//[thread start];
//第三种方法:队列
/* NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//操作数
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//使用主队列来回到主线程
//在主线程上修改UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//修改UI界面
[self setImage:image];
}];
}];
[queue addOperation:op];
*/
//----------------GCD---------------
// //1.创建Queue
// dispatch_queue_t queue = dispatch_queue_create("com.xw.gcd.queue", DISPATCH_QUEUE_CONCURRENT);//并行队列
//
// //2.创建要执行的任务,加到队列中
// dispatch_async(queue, ^{
//
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
// [self setImage:image];
// });
//用系统给的queue---
// (两个参数)
//参数1:优先级
//参数2:标识符
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{
//请求数据
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//显示在UI界面上
dispatch_async(dispatch_get_main_queue(), ^{
//UI相关的代码
//UI界面的刷新最好回到主线程中
[self setImage:image];
});
});
}
- (void)loadImage:(NSURL *)url{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self setImage:image];
}
@end
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。