// 下载 - > 合并 - > 显示
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 组 // 一个并行队列队列中 有两个任务 然后放入一个组中
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
__block UIImage *image1 = nil;
dispatch_group_async(group,queue, ^{
NSString *urlString1 = [NSString stringWithFormat:@"http://img04.tooopen.com/images/20130712/tooopen_17270713.jpg"];
NSURL *url1 = [NSURL URLWithString:urlString1];
image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url1]];
});
__block UIImage *image2 = nil;
dispatch_group_async(group,queue, ^{
NSString *urlString2 = [NSString stringWithFormat:@"https://www.baidu.com/img/bd_logo1.png"];
NSURL *url2 = [NSURL URLWithString:urlString2];
image2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url2]];
});
// 保证执行完组里面的所有任务之后,再执行notify函数里面的block
dispatch_group_notify(group, queue, ^{
UIGraphicsBeginImageContextWithOptions(image1.size, NO, 0.0f);
[image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
[image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];
UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = fullImage;
});
UIGraphicsEndImageContext();
});
#if 0
// @"http://img04.tooopen.com/images/20130712/tooopen_17270713.jpg"
// @"https://www.baidu.com/img/bd_logo1.png"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 下载第一张
NSString *urlString1 = [NSString stringWithFormat:@"http://img04.tooopen.com/images/20130712/tooopen_17270713.jpg"];
NSURL *url1 = [NSURL URLWithString:urlString1];
self.image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url1]];
NSLog(@"---%@---",[NSThread currentThread]);
[self bindImages];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 下载第二张
NSString *urlString2 = [NSString stringWithFormat:@"https://www.baidu.com/img/bd_logo1.png"];
NSURL *url2 = [NSURL URLWithString:urlString2];
self.image2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url2]];
NSLog(@"---%@---",[NSThread currentThread]);
[self bindImages];
});
#endif
}
- (void)bindImages {
if (self.image1 == nil || self.image2 == nil) {
UIGraphicsBeginImageContextWithOptions(self.image1.size, NO, 0.0f);
[self.image1 drawInRect:CGRectMake(0, 0, self.image1.size.width, self.image1.size.height)];
[self.image2 drawInRect:CGRectMake(0, 0, self.image2.size.width, self.image2.size.height)];
UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = fullImage;
});
UIGraphicsEndImageContext();
} else return;
}
GCD队列组2
最新推荐文章于 2015-08-13 16:30:33 发布