cocoa ios iphone xcode 播放GIF動畫 – iPhone手機開發技術文章 iPhone軟體開發教學課程

使用imageio的這個自帶的framework, 這個庫也是apple的webkit所使用的,可以參考apple的opensource的webkit實現。 因此,這個 庫從性能和蒹容性方面應該都是最佳選擇

以下是代碼,比較簡單

NSDictionary *gifLoopCount = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithInt:0] , (NSString *)kCGImagePropertyGIFLoopCount,nil
                                  ];
   
    NSDictionary * gifProperties = [NSDictionary dictionaryWithObject:gifLoopCount forKey:(NSString *)kCGImagePropertyGIFDictionary] ;
   
    CGImageSourceRef gif = CGImageSourceCreateWithData((__bridge  CFDataRef)(data), (__bridge  CFDictionaryRef)gifProperties);
   
   
    CFDictionaryRef gifprops =(CGImageSourceCopyPropertiesAtIndex(gif,0,NULL));
   
    NSInteger count =CGImageSourceGetCount(gif);
   
    CFDictionaryRef  gifDic = CFDictionaryGetValue(gifprops, kCGImagePropertyGIFDictionary);//[gifprops objectForKey:(NSString *)kCGImagePropertyGIFDictionary];
   
    NSNumber * delay = CFDictionaryGetValue(gifDic, kCGImagePropertyGIFDelayTime); //[gifDic objectForKey:(NSString *)kCGImagePropertyGIFDelayTime];
    NSNumber * w = CFDictionaryGetValue(gifprops, @"PixelWidth");
    NSNumber * h =CFDictionaryGetValue(gifprops, @"PixelHeight");
    totalDuration  = delay.doubleValue * count;
    pixelWidth = w.intValue;
    pixelHeight = h.intValue;
   
 
    images = [[NSMutableArray alloc] init];
    for(int index=0;index<count;index++)
    {
        CGImageRef ref = CGImageSourceCreateImageAtIndex(gif, index, nil);
        UIImage *img = [UIImage imageWithCGImage:ref];
        [images addObject:img];
        CFRelease(ref);
    }
   
    CFRelease(gifprops);
    CFRelease(gif);

解壓完之後,直接用IMageview就可以播放瞭。代碼如下。
    UIImageView *image = ….;
    image.animationDuration = totalDuration;
    image.animationImages = images;
    [image startAnimating]

 

發佈留言