iOS下载两张图片再合成图片

  • 对于图片下载有很多方法,下载图片再合成,主要是需要监听到图片下载完成。可以使用GCD的信号量或者使用GCD组都比较方便

  • 这里需要注意一下,就是当我们用SDWebImage下载图片的时候,这时候下载图片是开启了异步下载,所以我们需要拿到图片下载完成的回调才行

  • 代码如下:

- (void)imagesGroup
{
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(0, 100, self.view.bounds.size.width, 400);
    imageView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:imageView];
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("cn.gcd-group.www", DISPATCH_QUEUE_CONCURRENT);

    dispatch_group_async(group, queue, ^{
        NSLog(@"第1张图片");
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic31.nipic.com/20130801/11604791_100539834000_2.jpg"]];
        NSLog(@"第1张图片下载完毕");
        self.imageOne = [UIImage imageWithData:data];
    });
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"第2张图片");
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic37.nipic.com/20140113/8800276_184927469000_2.png"]];
        NSLog(@"第2张图片下载完毕");
        self.imageTwo = [UIImage imageWithData:data];
    });
   
    dispatch_group_notify(group, queue, ^{
        UIGraphicsBeginImageContext(CGSizeMake(300, 400));
        
        [self.imageOne drawInRect:CGRectMake(0, 100, 150, 400)];
        [self.imageTwo drawInRect:CGRectMake(150, 100, 150, 400)];
        
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            imageView.image = newImage;
    
            NSLog(@"---->图片合并完毕");
        });
    });
}

你可能感兴趣的:(iOS下载两张图片再合成图片)