- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self downloadImage]; } -(void)downloadImage{ dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_group_async(group, queue, ^{ NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530167525247&di=f09b0f4412a2825e4ae641079691cd14&imgtype=0&src=http%3A%2F%2Fpic35.photophoto.cn%2F20150617%2F0013026499624253_b.png"]; NSData *data = [NSData dataWithContentsOfURL:url]; self.image1 = [UIImage imageWithData:data]; }); dispatch_group_async(group, queue, ^{ NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530167525247&di=184be5b28b34bf0670e9cb065fef673c&imgtype=0&src=http%3A%2F%2Fpic22.nipic.com%2F20120724%2F16351_204302573152_2.png"]; NSData *data = [NSData dataWithContentsOfURL:url]; self.image2 = [UIImage imageWithData:data]; }); dispatch_group_notify(group,queue , ^{ //1创建图形上下文 UIGraphicsBeginImageContext(CGSizeMake(200, 200)); //2.画图 [self.image1 drawInRect:CGRectMake(0, 0, 200, 100)]; self.image1 = nil;//此时不需要图片了 //3.画图 [self.image2 drawInRect:CGRectMake(0, 100, 200, 100)]; self.image2 = nil;//此时不需要图片了 //4.从图形上下文获取图片 UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext(); //5.关闭上下文 UIGraphicsEndImageContext(); //6更新UI dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = tempImage; }); }); }
swift 版 下载图片
//保证 下载完图片在分享 private func getDownloadImage(urlStrArr:[String], block:@escaping (_ imageArr:[UIImage])->()){ var downloadImageArr : [UIImage] = [] var tempBlock : ((_ imageArr:[UIImage])->())? = nil tempBlock = block let group = DispatchGroup() let diyQueue = DispatchQueue(label: "diyQueue") for (_, urlStr) in urlStrArr.enumerated(){ group.enter() diyQueue.async { if let tempUrl = URL.init(string: urlStr){ if let tempData = try? Data.init(contentsOf: tempUrl){ if let tempImage = UIImage.init(data: tempData){ downloadImageArr.append(tempImage) group.leave() } } } } } //走完队列 group.notify(queue: diyQueue) { //这个地方可以合并数据, 图片合并操作等等 //主线程刷新 DispatchQueue.main.async { tempBlock?(downloadImageArr) } } }
调用
getDownloadImage(urlStrArr: [dataStruct.relationQrCodeUrl]) { [weak self](imageArr:[UIImage]) in self?.downloadView.updateImage(downImage: imageArr[0]) }