您的位置:首页 > 其它

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

2014-12-12 14:42 357 查看
话不多说,直接上代码

- (void)viewDidLoad {
    [super
viewDidLoad];
    
//    _imageURL = [imageURLS retain];
    
    _request = [[NSURLRequest
alloc] initWithURL:[NSURL
URLWithString:@"http://avatar.csdn.net/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{

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  imageIO