#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
/** 图片1*/
@property(nonatomic ,strong) UIImage *image1;
/** 图片2*/
@property(nonatomic ,strong) UIImage *image2;
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//2.封装下载图片1的操作
NSBlockOperation *download1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1----%@",[NSThread currentThread]);
NSURL *url = [NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201408/11/20140811113003_GQSHJ.thumb.700_0.jpeg"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.image1 = [UIImage imageWithData:data];
}];
//3.封装下载图片2的操作
NSBlockOperation *download2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"2----%@",[NSThread currentThread]);
NSURL *url = [NSURL URLWithString:@"http://img.news.d.cn/UE/net/UEUpload/6354613671553125003994450.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.image2 = [UIImage imageWithData:data];
}];
//3.合成图片
NSBlockOperation *combie = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"3----%@",[NSThread currentThread]);
UIGraphicsBeginImageContext(CGSizeMake(200, 200));
[self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
[self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//4.回到主线程刷新UI
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.imageView.image = image;
}];
}];
//添加依赖
[combie addDependency:download1];
[combie addDependency:download2];
//5.把操作添加到队列
[queue addOperation:download1];
[queue addOperation:download2];
[queue addOperation:combie];
}
-(void)download
{
//1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
//2.封装下载图片的操作
NSBlockOperation *download = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1----%@",[NSThread currentThread]);
NSURL *url = [NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201408/11/20140811113003_GQSHJ.thumb.700_0.jpeg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//3.回到主线程刷新UI
//addOperationWithBlock:内部会将操作先包装成NSBlockOperation,然后添加打牌队列中
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"UI----%@",[NSThread currentThread]);
self.imageView.image = image;
}];
}];
//3.把操作添加到队列
[queue addOperation:download];
}
@end