美文网首页
iOS 渐进式加载图片

iOS 渐进式加载图片

作者: 踏云小子 | 来源:发表于2018-02-26 17:39 被阅读213次
#import "MainViewController.h"
#import <ImageIO/ImageIO.h>
#import <CoreFoundation/CoreFoundation.h>

@interface MainViewController ()<NSURLConnectionDelegate>{
    CGImageSourceRef _incrementalImgSource;
}
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) NSURLConnection *connection;
@property (nonatomic, retain) NSMutableData *data;
@property (nonatomic, assign) BOOL isFinished;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)onClickLoad:(id)sender {
    _incrementalImgSource = CGImageSourceCreateIncremental(NULL);
    
    NSString *url = @"https://i.pinimg.com/1200x/2e/0c/c5/2e0cc5d86e7b7cd42af225c29f21c37f.jpg";
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
    _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    NSInteger expected = (NSInteger)response.expectedContentLength;
    expected = expected > 0 ? expected : 0;
    _data = [NSMutableData dataWithCapacity:expected];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"didReceiveData");
    [_data appendData:data];
    CGImageSourceUpdateData(_incrementalImgSource, (CFDataRef)_data, _isFinished);
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementalImgSource, 0, NULL);
    self.imageView.image = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"connectionDidFinishLoading");
    _isFinished = YES;
    CGImageSourceUpdateData(_incrementalImgSource, (CFDataRef)_data, _isFinished);
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementalImgSource, 0, NULL);
    self.imageView.image = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection{
    return NO;
}

首页用CGImageSourceCreateIncremental(NULL)创建一个空的图片源,
随后获取到图片用CGImageSourceUpdateData更新图像数据
CGImageSourceCreateImageAtIndex创建CGImageRef对象,以显示图片

相关文章

网友评论

      本文标题:iOS 渐进式加载图片

      本文链接:https://www.haomeiwen.com/subject/bggyxftx.html