Created
October 15, 2012 19:53
-
-
Save andrei512/3894888 to your computer and use it in GitHub Desktop.
GIFLoader - simple GIF support for iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GIFLoader.h | |
// AnimatedGifExample | |
// | |
// Created by Andrei on 10/15/12. | |
// Copyright (c) 2012 Whatevra. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface GIFLoader : NSObject | |
+ (void)loadGIFFrom:(NSString *)url to:(UIImageView *)imageView; | |
+ (void)loadGIFData:(NSData *)data to:(UIImageView *)imageView; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GIFLoader.m | |
// AnimatedGifExample | |
// | |
// Created by Andrei on 10/15/12. | |
// Copyright (c) 2012 Whatevra. All rights reserved. | |
// | |
#import "GIFLoader.h" | |
#import <ImageIO/ImageIO.h> | |
@implementation GIFLoader | |
+ (void)loadGIFFrom:(NSString *)url to:(UIImageView *)imageView { | |
NSData *gifData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]]; | |
[self loadGIFData:gifData to:imageView]; | |
} | |
+ (void)loadGIFData:(NSData *)data to:(UIImageView *)imageView { | |
NSMutableArray *frames = nil; | |
CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)data, NULL); | |
CGFloat animationTime = 0.f; | |
if (src) { | |
size_t l = CGImageSourceGetCount(src); | |
frames = [NSMutableArray arrayWithCapacity:l]; | |
for (size_t i = 0; i < l; i++) { | |
CGImageRef img = CGImageSourceCreateImageAtIndex(src, i, NULL); | |
NSDictionary *properties = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(src, i, NULL); | |
NSDictionary *frameProperties = [properties objectForKey:(NSString *)kCGImagePropertyGIFDictionary]; | |
NSNumber *delayTime = [frameProperties objectForKey:(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; | |
animationTime += [delayTime floatValue]; | |
if (img) { | |
[frames addObject:[UIImage imageWithCGImage:img]]; | |
CGImageRelease(img); | |
} | |
} | |
CFRelease(src); | |
} | |
[imageView setImage:[frames objectAtIndex:0]]; | |
[imageView setAnimationImages:frames]; | |
[imageView setAnimationDuration:animationTime]; | |
[imageView startAnimating]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very clean, thanks! I have a gif in a UICollectionView and upon entering the view it locks up the system until it processes it from url. Everytime you scroll off and back down you get a good 1 second skip.
Throwing it in a thread shows white and takes ~20 seconds before it pops up.
Is there a good solution to this?