當(dāng)我們網(wǎng)絡(luò)加載GIF桨醋,或者獲取到本地GIF的數(shù)據(jù)data時,可以將data轉(zhuǎn)換成動圖UIImage
//獲取動圖
+ (UIImage *)animatedGIFWithData:(NSData *)data {
? ? if(!data) {
? ? ? ? return?nil;
? ? }
//獲取動圖源數(shù)據(jù)
? ? CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
//獲取動圖圖片集數(shù)量
? ? size_t count = CGImageSourceGetCount(source);
? ? UIImage * animatedImage;
//如果圖片集只有一張卿樱,那么直接創(chuàng)建成一張圖片,否則合成一個動圖
? ? if(count <=1) {
? ? ? ? animatedImage = [[UIImage alloc]initWithData:data];
? ? }else?{
? ? ? ? NSMutableArray * images = [NSMutableArray array];
//記錄動圖總時長
? ? ? ? NSTimeInterval duration =0.0f;
????????//遍歷每張圖片
? ? ? ? for(size_t i =0; i < count; i++) {
? ? ? ? ? ? CGImageRef image =CGImageSourceCreateImageAtIndex(source, i,NULL);
????????????//獲取單張動圖時間間距
? ? ? ? ? ? duration += [self?frameDurationAtIndex:i source:source];
? ? ? ? ? ? [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
? ? ? ? ? ? CGImageRelease(image);
? ? ? ? }
? ? ? ? //若未獲取到時長宠能,夸楣,自定義時長為0.1x張數(shù),抑月,這里可以根據(jù)需求自定義
? ? ? ? if(!duration) {
? ? ? ? ? ? duration = (1.0f/10.0f) * count;
? ? ? ? }
? ? ? ? //創(chuàng)建動圖
? ? ? ? animatedImage = [UIImage animatedImageWithImages:images duration:duration];
? ? }
? ? CFRelease(source);
? ? return?animatedImage;
}
+ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
? ? float?frameDuration =0.1f;
? ? CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index,nil);
? ? NSDictionary * frameProperties = (__bridgeNSDictionary*)cfFrameProperties;
? ? NSDictionary * gifProperties = frameProperties[(NSString*)kCGImagePropertyGIFDictionary];
? ? NSNumber * delayTimeUnclampedProp = gifProperties[(NSString*)kCGImagePropertyGIFUnclampedDelayTime];
? ? if(delayTimeUnclampedProp) {
? ? ? ? frameDuration = [delayTimeUnclampedProp floatValue];
? ? }
? ? else{
? ? ? ? NSNumber * delayTimeProp = gifProperties[(NSString*)kCGImagePropertyGIFDelayTime];
? ? ? ? if(delayTimeProp) {
? ? ? ? ? ? frameDuration = [delayTimeProp floatValue];
? ? ? ? }
? ? }?
? ? CFRelease(cfFrameProperties);
? ? return?frameDuration;
}