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

来源:互联网 发布:飞机时刻表查询软件 编辑:程序博客网 时间:2024/06/06 20:54

- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath{

    

   self = [superinitWithFrame:frame];

   if (self) {

        

       /*

         *_filePath :    gif路径

         *data :    取得这个gif

         */

       NSData *data = [NSDatadataWithContentsOfFile:_filePath];

       /*

         *gifLoopCount  : 设置一个gif的循环属性 ,值为0

         */

       NSDictionary *gifLoopCount = [NSDictionarydictionaryWithObjectsAndKeys:

                                      [NSNumbernumberWithInt:0] , (NSString *)kCGImagePropertyGIFLoopCount,nil

                                      ];

       /*

         *创建gif属性

         */

        NSDictionary * gifProperties = [NSDictionarydictionaryWithObject:gifLoopCountforKey:(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原理,但经过我试验, DelayTimeUnclampedDelayTime应该是取UnclampedDelayTime做出来的图才和用浏览器打开的时间相同

        

        NSTimer *timer = [NSTimerscheduledTimerWithTimeInterval:delay.floatValuetarget:selfselector:@selector(play)userInfo:nilrepeats:YES];

        [timerfire];

        

       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;

    [superremoveFromSuperview];

}

- (void)dealloc {

    NSLog(@"dealloc");

    CFRelease(gif);

    [gifProperties release];

    [superdealloc];

}

0 0
原创粉丝点击