首先说一下我们的需求是这样的,第一步要在服务端下载两张图片,之后把小图片绘制到大图片上去(就是让小图片成为大图片的水印),之后我们通过分析可以知道下载两张图片属于耗时操作,而制作水印的操作相对来说耗时不多,我们有必须把制作水印的操作在下载完成两张图片之后完成(不解释),但是这样虽然在异步线程中完成的,不过,当下载完第一个图的时候,第二个图还没下,在等待,我们想让每一个图都在一个单独的异步线程里面下载,我之前就是这样做的,数据量大的时候比较耗时,于是我在网上找到了第二种方法 -- 就是用队列组的方式实现该操作:
- #import <UIKit/UIKit.h>
- @interface htingViewController : UIViewController
- @end
- #import "htingViewController.h"
- @interface htingViewController ()
- //用来显示两张图片的ImageView
- @property (weak, nonatomic) IBOutlet UIImageView *imageView;
- @end
- @implementation htingViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- }
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
- // 1.队列组
- dispatch_group_t group = dispatch_group_create();
- dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
- // 2.下载图片1
- __block UIImage *image1 = nil; //要加一个 __block因为 block代码默认不能改外面的东西(记住语法即可)
- dispatch_group_async(group, queue, ^{
- NSURL *url1 = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494ee460de6182ff5e0fe99257e80.jpg"];
- NSData *data1 = [NSData dataWithContentsOfURL:url1];
- image1 = [UIImage imageWithData:data1];
- });
- // 3.下载图片2
- __block UIImage *image2 = nil;
- dispatch_group_async(group, queue, ^{
- NSURL *url2 = [NSURL URLWithString:@"http://su.bdimg.com/static/superplus/img/logo_white_ee663702.png"];
- NSData *data2 = [NSData dataWithContentsOfURL:url2];
- image2 = [UIImage imageWithData:data2];
- });
- // 4.合并图片 用Quartz2D的知识,则要先要搞一个空的大图片,然后再把小图片画上去(保证执行完组里面的所有任务之后,再执行notify函数里面的block)
- //队列组:要把队列组里面的所有任务都执行完后调用dispatch_group_notify(group, queue, ^{ }
- dispatch_group_notify(group, queue, ^{
- // 开启一个位图上下文
- UIGraphicsBeginImageContextWithOptions(image1.size, NO, 0.0);
- // 绘制第1张图片
- CGFloat image1W = image1.size.width;
- CGFloat image1H = image1.size.height;
- [image1 drawInRect:CGRectMake(0, 0, image1W, image1H)];
- // 绘制第2张图片
- CGFloat image2W = image2.size.width * 0.5;
- CGFloat image2H = image2.size.height * 0.5;
- CGFloat image2Y = image1H - image2H;
- [image2 drawInRect:CGRectMake(0, image2Y, image2W, image2H)];
- // 得到上下文中的图片
- UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
- // 结束上下文
- UIGraphicsEndImageContext();
- // 5.回到主线程显示图片
- dispatch_async(dispatch_get_main_queue(), ^{
- self.imageView.image = fullImage;
- });
- });
- }
- @end
这样轻松解决,这种方法不但省时间,看着还条理清