您的位置:首页 > 移动开发 > IOS开发

iOS-使用系统类库加载gif格式图片

2014-11-05 20:13 423 查看
- (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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gif ios iOS加载gif图片