@interface ViewController ()
@property (nonatomic,strong)UIImage *image1;
@property (nonatomic,strong)UIImage *image2;
@end
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
/*
//1.下载图片1
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:@"图片"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
});
//2.下载图片2
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:@"图片"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
});
// 方法一:拦截方法,保证前两个任务完成,再做3.图片合成
//并发队列不知道前面谁先请求下来,所以加dispatch_barrier_async
//dispatch_barrier_async(, <#^(void)block#>)
//3.将图片1,图片2合成一张新的图片
//4.将新图片显示出来
*/
// 方法二:
// 创建一个队列组
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSURL *url = [NSURL URLWithString:@"图片"];
NSData *data = [NSData dataWithContentsOfURL:url];
_image1 = [UIImage imageWithData:data];
});
dispatch_group_async(group, queue, ^{
NSURL *url = [NSURL URLWithString:@"图片"];
NSData *data = [NSData dataWithContentsOfURL:url];
_image2 = [UIImage imageWithData:data];
});
//3.将图片1,图片2合成一张新的图片
// 任务一和任务二都执行完,才执行dispatch_group_notify
dispatch_group_notify(group, queue, ^{
// 开启新的图像上下文
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
//绘制图片
[self.image1 drawInRect:CGRectMake(0, 0, 50, 100)];
[self.image2 drawInRect:CGRectMake(50, 0, 50, 100)];
//取得上下文图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//结束上下文
UIGraphicsEndImageContext();
//回到主线程显示图片
dispatch_async(dispatch_get_main_queue(), ^{
//4将图片显示过来,到storyboard
self.imageView.image = image;
});
});
}