Skip to content

Instantly share code, notes, and snippets.

@lawrencelomax
Created January 24, 2012 15:09
Show Gist options
  • Save lawrencelomax/1670617 to your computer and use it in GitHub Desktop.
Save lawrencelomax/1670617 to your computer and use it in GitHub Desktop.
Simple progressive image loading
UIView * view = [[UIView alloc] initWithFrame:CGRectMake( 0.0f, 0.0f, kAffirmationThumbnailWidth, kAffirmationThumbnailHeight )];
view.backgroundColor = [UIColor grayColor];
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kAffirmationThumbnailWidth, kAffirmationThumbnailHeight)];
imageView.backgroundColor = [UIColor clearColor];
imageView.alpha = 1.0;
[view addSubview:imageView];
// Background getting of small image and loading into memory
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSString * imagePathSmall = [NSString stringWithFormat:@"%@_small.jpg",[[affirmation imagePath] stringByDeletingPathExtension]];
NSData * dataSmall = [NSData dataWithContentsOfFile:imagePathSmall];
UIImage * imageSmall = [UIImage imageWithData:dataSmall];
[imageSmall forceLoad];
// Image is loaded, set outlet on main thread
dispatch_sync(dispatch_get_main_queue(), ^(void){
imageView.image = imageSmall;
//Load larger image
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){
NSString * imagePathLarger = [affirmation imagePath];
NSData * dataLarger = [NSData dataWithContentsOfFile:imagePathLarger];
UIImage * imageLarger = [UIImage imageWithData:dataLarger];
[imageLarger forceLoad];
// Set outlet again on main thread
dispatch_sync(dispatch_get_main_queue(), ^(void){
imageView.image = imageLarger;
});
});
// Fade Animation
[UIView animateWithDuration:0.2
delay:0
options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveEaseInOut)
animations:^(void){
imageView.alpha = 1.0;
}
completion:nil];
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment