//獲取gif圖片的總時長和循環(huán)次數(shù)
- (NSTimeInterval)durationForGifData:(NSData *)data{
//將GIF圖片轉(zhuǎn)換成對應(yīng)的圖片源
CGImageSourceRef gifSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
//獲取其中圖片源個數(shù)厅缺,即由多少幀圖片組成
size_t frameCout = CGImageSourceGetCount(gifSource);
//定義數(shù)組存儲拆分出來的圖片
NSMutableArray* frames = [[NSMutableArray alloc] init];
NSTimeInterval totalDuration = 0;
for (size_t i=0; i<frameCout; i++) {
//從GIF圖片中取出源圖片
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
//將圖片源轉(zhuǎn)換成UIimageView能使用的圖片源
UIImage* imageName = [UIImage imageWithCGImage:imageRef];
//將圖片加入數(shù)組中
[frames addObject:imageName];
NSTimeInterval duration = [self gifImageDeleyTime:gifSource index:i];
totalDuration += duration;
CGImageRelease(imageRef);
}
//獲取循環(huán)次數(shù)
NSInteger loopCount;//循環(huán)次數(shù)
CFDictionaryRef properties = CGImageSourceCopyProperties(gifSource, NULL);
if (properties) {
CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
if (gif) {
CFTypeRef loop = CFDictionaryGetValue(gif, kCGImagePropertyGIFLoopCount);
if (loop) {
//如果loop == NULL渴频,表示不循環(huán)播放翅娶,當loopCount == 0時,表示無限循環(huán);
CFNumberGetValue(loop, kCFNumberNSIntegerType, &loopCount)
};
}
}
CFRelease(gifSource);
return totalDuration;
}
循環(huán)次數(shù)的鍵:kCGImagePropertyGIFLoopCount
無限循環(huán)播放.png
不循環(huán)播放.png
時間間隔的鍵:kCGImagePropertyGIFUnclampedDelayTime
每一幀時間間隔.png
//獲取GIF圖片每幀的時長
- (NSTimeInterval)gifImageDeleyTime:(CGImageSourceRef)imageSource index:(NSInteger)index {
NSTimeInterval duration = 0;
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, NULL);
if (imageProperties) {
CFDictionaryRef gifProperties;
BOOL result = CFDictionaryGetValueIfPresent(imageProperties, kCGImagePropertyGIFDictionary, (const void **)&gifProperties);
if (result) {
const void *durationValue;
if (CFDictionaryGetValueIfPresent(gifProperties, kCGImagePropertyGIFUnclampedDelayTime, &durationValue)) {
duration = [(__bridge NSNumber *)durationValue doubleValue];
if (duration < 0) {
if (CFDictionaryGetValueIfPresent(gifProperties, kCGImagePropertyGIFDelayTime, &durationValue)) {
duration = [(__bridge NSNumber *)durationValue doubleValue];
}
}
}
}
}
return duration;
}