imageIO 实现渐进加载图片的效果

本文介绍了一种iOS应用中实现渐进式图片加载的方法。通过NSURLConnection接收数据,并使用CGImageSource创建增量图像源来逐步显示图片内容,从而提升用户体验。



话不多说,直接上代码



- (void)viewDidLoad {

    [super viewDidLoad];

    

//    _imageURL = [imageURLS retain];

    

    _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://avatar.youkuaiyun.com/2/C/D/1_totogo2010.jpg"]];

    _conn    = [[NSURLConnection alloc] initWithRequest:_request delegate:self];

    

    _incrementallyimgSource = CGImageSourceCreateIncremental(NULL);

    

    _recieveData = [[NSMutableData alloc] init];

    _isLoadFinished = false;



    view = [[UIImageView alloc] initWithFrame:CGRectMake(10,10, 300, 300)];

    

    view.image = self.image;

    [self.view addSubview:view];

    

}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{


    _expectedLeght = response.expectedContentLength;

    NSLog(@"expected Length: %lld", _expectedLeght);

    NSString *mimeType = response.MIMEType;

    NSLog(@"MIME TYPE %@", mimeType);

    

    NSArray * arr = [mimeType componentsSeparatedByString:@"/"];

    if (arr.count < 1 || ![[arr objectAtIndex:0] isEqual:@"image"]) {

        NSLog(@"not a image url");

        [connection cancel];

        [_conn release]; _conn = nil;

    }

    

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{


     [_recieveData appendData:data];

    _isLoadFinished = false;

    if (_expectedLeght == _recieveData.length) {

        _isLoadFinished = true;

    }

    CGImageSourceUpdateData(_incrementallyimgSource, (CFDataRef)_recieveData, _isLoadFinished);

    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyimgSource, 0, NULL);

    view.image = [UIImage imageWithCGImage:imageRef];

//    [self.view addSubview:view];

    CGImageRelease(imageRef);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{


    if (!_isLoadFinished) {

        CGImageSourceUpdateData(_incrementallyimgSource, (CFDataRef)_recieveData, _isLoadFinished);

        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyimgSource, 0, NULL);

        view.image = [UIImage imageWithCGImage:imageRef];

        CGImageRelease(imageRef);

        [view setNeedsLayout];

    }

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{



}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值