UIImageView+Kit.h文件
#import
NS_ASSUME_NONNULL_BEGIN
@interface UIImageView (Kit)
- (void)loadGIFImageNamed:(NSString *)name;
@end
NS_ASSUME_NONNULL_END
#import "UIImageView+Kit.h"
@implementation UIImageView (Kit)
- (void)loadGIFImageNamed:(NSString *)name {
? ? /// 找到GIF圖片文件路徑
? ? NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:name withExtension:@"gif"];
? ? /// 將GIF圖片轉(zhuǎn)換成對(duì)應(yīng)的圖片資源
? ? CGImageSourceRefimageSourceRef =CGImageSourceCreateWithURL((__bridgeCFURLRef)fileUrl,NULL);
? ? /// 從圖片資源中獲取圖片幀數(shù)妈踊,即由多少圖片元素組成(注:GIF圖片本質(zhì)是有多張圖片合成流動(dòng)圖片)
? ? size_timageCount =CGImageSourceGetCount(imageSourceRef);
? ? /// 定義數(shù)組拆分圖片源
? ? NSMutableArray*images = [NSMutableArrayarrayWithCapacity:imageCount];
? ? /// 定義動(dòng)畫持續(xù)時(shí)長(zhǎng)
? ? floatanimationDuration =0.f;
? ? /// 循環(huán)獲取圖片元素
? ? for(size_ti =0; i < imageCount; i++) {
? ? ? ? /// 從圖片資源中取出圖片元素名段,即每一幀的圖片
? ? ? ? CGImageRefimageRef =CGImageSourceCreateImageAtIndex(imageSourceRef, i ,NULL);
? ? ? ? ///圖片轉(zhuǎn)換
? ? ? ? UIImage*image = [UIImageimageWithCGImage:imageRef];
? ? ? ? ///存儲(chǔ)圖片
? ? ? ? [imagesaddObject:image];
? ? ? ? ///獲取元素圖片的信息
? ? ? ? NSDictionary*imageElementInfo = (__bridgeNSDictionary*)CGImageSourceCopyProperties(imageSourceRef,NULL);
? ? ? ? ///獲取元素動(dòng)畫信息
? ? ? ? NSDictionary*imageElementGIFInfo = [imageElementInfoobjectForKey:(__bridgeNSString*)kCGImagePropertyGIFDictionary];
? ? ? ? /// 初始化每幀之間間隔的屬性。
? ? ? ? CGFloatduration =0.1f;
? ? ? ? NSNumber*unclampedDelayTime = [imageElementGIFInfoobjectForKey:(__bridgeNSString*)kCGImagePropertyGIFUnclampedDelayTime];
? ? ? ? if(unclampedDelayTime) {
? ? ? ? ? ? duration= unclampedDelayTime.floatValue;
? ? ? ? }else{
? ? ? ? ? ? NSNumber*delayTime = [imageElementGIFInfoobjectForKey:(__bridgeNSString*)kCGImagePropertyGIFDelayTime];
? ? ? ? ? ? if(delayTime) {
? ? ? ? ? ? ? ? duration= delayTime.floatValue;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? /// 獲取延遲時(shí)間可能為0.f
? ? ? ? if(duration <=0.011f) duration =0.100f;
? ? ? ? animationDuration += duration;
? ? ? ? ///釋放內(nèi)存
? ? ? ? CGImageRelease(imageRef);
? ? }
? ? /// 圖片控件載入動(dòng)畫圖片數(shù)組
? ? self.animationImages= images;
? ? /// 設(shè)置動(dòng)畫持續(xù)時(shí)長(zhǎng)
? ? self.animationDuration= animationDuration;
? ? /// 設(shè)置動(dòng)畫重復(fù)次數(shù)
? ? self.animationRepeatCount = MAXFLOAT;
? ? ///開啟動(dòng)畫
? ? [self startAnimating];
}
@end