OC - GCD 队列组 - 下载图片画图

- (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;
        });
    });
}

猜你喜欢

转载自www.cnblogs.com/qingzZ/p/9237973.html
gcd