- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath{
self = [super initWithFrame:frame];
if (self) {
/*
*_filePath : gif路径
*data : 取得这个gif
*/
NSData *data = [NSData dataWithContentsOfFile:_filePath];
/*
*gifLoopCount : 设置一个gif的循环属性 ,值为0
*/
NSDictionary *gifLoopCount = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:0] , (NSString *)kCGImagePropertyGIFLoopCount,nil
];
/*
*创建gif属性
*/
NSDictionary * gifProperties = [NSDictionary dictionaryWithObject:gifLoopCount forKey:(NSString *)kCGImagePropertyGIFDictionary] ;
/*
*根据属性 还有data 得到gif,并存在CGImageSourceRef中
*{
* ColorModel = RGB;
* Depth = 8;//
* HasAlpha = 1;
* PixelHeight = 22;
* PixelWidth = 22;
* "{GIF}" = {
* DelayTime = "0.1";
* UnclampedDelayTime = "0.1";
* };
*}
*/
CGImageSourceRef gif = CGImageSourceCreateWithData((__bridge CFDataRef)(data), (__bridge CFDictionaryRef)gifProperties);
CFDictionaryRef gifprops =(CGImageSourceCopyPropertiesAtIndex(gif,0,NULL));
/*
*count : gif的张数
*/
NSInteger count =CGImageSourceGetCount(gif);
CFDictionaryRef gifDic = CFDictionaryGetValue(gifprops, kCGImagePropertyGIFDictionary);
/*
*delay: 延迟时间??
*/
NSNumber * delay = CFDictionaryGetValue(gifDic, kCGImagePropertyGIFDelayTime);
/*
*unclampedDelay: 延迟时间??
*/
NSNumber * unclampedDelay = CFDictionaryGetValue(gifDic, kCGImagePropertyGIFUnclampedDelayTime);
//注:本人不是做美术的,不懂gif原理,但经过我试验, DelayTime和UnclampedDelayTime 应该是取UnclampedDelayTime做出来的图才和用浏览器打开的时间相同
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:delay.floatValue target:self selector:@selector(play) userInfo:nil repeats:YES];
[timer fire];
CFRelease(gifprops);
CFRelease(gif);
}
}
-(void)play
{
index ++;
index = index%count;
CGImageRef ref = CGImageSourceCreateImageAtIndex(gif, index, (CFDictionaryRef)gifProperties);
self.layer.contents = (id)ref;
CFRelease(ref);
}
-(void)removeFromSuperview
{
NSLog(@"removeFromSuperview");
[timer invalidate];
timer = nil;
[super removeFromSuperview];
}
- (void)dealloc {
NSLog(@"dealloc");
CFRelease(gif);
[gifProperties release];
[super dealloc];
}