iOS实现图片边下载边显示

来源:互联网 发布:学页面美工要多少钱 编辑:程序博客网 时间:2024/05/22 10:48

iOS图片显示时使用Incremental方式解码就可以实现边下载边显示的效果,(SDWebImage没有使用这种方式,所以显示图片是一闪而出)。

具体做法是使用CGImageSoureceCreateIncremental(NULL)创建一个空的图片源,在下载图片时,每次获取到最新的Data时都将其更新到图片源并绘制,再更新UIImageView的图片。

代码如下:

#import "ViewController.h"


@interfaceViewController ()<NSURLSessionDataDelegate>

{

    UIImageView *bgImageView;

    NSMutableData *imageData;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    

    imageData = [NSMutableDatadata];

    

    bgImageView = [[UIImageViewalloc]initWithFrame:self.view.bounds];

    [self.viewaddSubview:bgImageView];

    

    NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration]delegate:selfdelegateQueue:[NSOperationQueuemainQueue]];

    NSURLSessionDataTask *task = [sessiondataTaskWithURL:[NSURLURLWithString:@"http://image155-c.poco.cn/mypoco/myphoto/20110117/00/20110117001006_1780564805.jpg"]];

    [task resume];

}



-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data

{

        UIImage *temImage =nil;

        //拼接历史图片数据

        [imageDataappendData:data];

        //创建空图片空间

        CGImageSourceRef emptySpace =CGImageSourceCreateIncremental(NULL);

        //更新图片空间数据

        CGImageSourceUpdateData(emptySpace, (CFDataRef)imageData,false);

        //绘制图片

        CGImageRef image =CGImageSourceCreateImageAtIndex(emptySpace, 0,NULL);

        //CGImageRef -> UIImage

        temImage = [UIImageimageWithCGImage:imagescale:1.0orientation:UIImageOrientationUp];

        //释放图片空间

        CFRelease(emptySpace);

        //更新图片

        [bgImageViewsetImage:temImage];

}


-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

{

    if (!error) {

        NSLog(@"下载完成");

    } else {

        NSLog(@"下载发生错误");

    }

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



@end