Skip to content

Instantly share code, notes, and snippets.

@majie1993
Created December 26, 2014 04:10
Show Gist options
  • Save majie1993/9475b27eee84ce41f151 to your computer and use it in GitHub Desktop.
Save majie1993/9475b27eee84ce41f151 to your computer and use it in GitHub Desktop.
Display a GIF in UIImageView
//
// UIImageView+loadGif.m
// GifTest
//
// Created by WaterWood on 14-5-21.
#import "UIImageView+loadGif.h"
#import <QuartzCore/QuartzCore.h>
#import <ImageIO/ImageIO.h>
@implementation UIImageView (loadGif)
- (void)setGifFilePath:(NSString*)gifFilePath
{
NSData *gifData = [NSData dataWithContentsOfFile:gifFilePath];
NSMutableArray *frames = nil;
CGImageSourceRef src = CGImageSourceCreateWithData((__bridge CFDataRef)gifData, NULL);
double total = 0;
NSTimeInterval gifAnimationDuration;
if (src)
{
size_t l = CGImageSourceGetCount(src);
if (l > 1)
{
frames = [NSMutableArray arrayWithCapacity: l];
for (size_t i = 0; i < l; i++)
{
CGImageRef img = CGImageSourceCreateImageAtIndex(src, i, NULL);
CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(src, 0, NULL);
NSDictionary *dict = [NSDictionary dictionaryWithDictionary:CFBridgingRelease(dic)];
if (dict){
NSDictionary *tmpdict = [dict objectForKey: @"{GIF}"];
total += [[tmpdict objectForKey: @"DelayTime"] doubleValue] * 100;
}
if (img) {
[frames addObject: [UIImage imageWithCGImage: img]];
CGImageRelease(img);
}
}
gifAnimationDuration = total / 100;
self.animationImages = frames;
self.animationDuration = gifAnimationDuration;
[self startAnimating];
}
else if(l == 1)
{
CGImageRef img = CGImageSourceCreateImageAtIndex(src, 0, NULL);
self.image = [UIImage imageWithCGImage:img];
CGImageRelease(img);
}
}
CFBridgingRelease(src);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment