1. 程式人生 > >iOS開發之初:根據一張gif圖,返回其中每一幀的圖片陣列(ImageView載入gif))

iOS開發之初:根據一張gif圖,返回其中每一幀的圖片陣列(ImageView載入gif))

在APP開發過程中能用到gif圖的地方無非就是重新整理和載入動畫了(等用到小動畫的地方).但是UIImageView是無法直接載入gif圖的,ImageView提供了一個載入動畫圖片陣列的方法..那要有很多幀.png/.jpg的圖片才行…但是像我這種沒有美工的開發,網上只找了一張gif圖怎麼辦….
為陣列類別,新增一個類方法–由一張專案中的gif圖的名字返回其中很多幀UIImage的陣列.

@interface NSArray (CDIExtention)
/** 將一個gif圖轉換為一幀一幀的圖片陣列*/
+ (NSArray *)cdi_imagesWithGif:(NSString *)gifNameInBoundle;

匯入ImageIO框架
(1) 獲取到GIF圖的源資料 CGImageSourceRef

CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)fileUrl, NULL);

(2) 由源資料 SourceRef生成一張CGImageRef型別圖片

 CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);

(3) 有CGImageRef生成UIImage ,我們想要的.

 UIImage *image = [UIImage
imageWithCGImage:imageRef];

.m檔案內容如下,最好要返回陣列,方便ImageView擷取陣列哪一段進行動畫

#import <ImageIO/ImageIO.h>
@implementation NSArray (CDIExtention)

+ (NSArray *)cdi_imagesWithGif:(NSString *)gifNameInBoundle {
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:gifNameInBoundle withExtension:@"gif"
]; CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)fileUrl, NULL); size_t gifCount = CGImageSourceGetCount(gifSource); NSMutableArray *frames = [[NSMutableArray alloc]init]; for (size_t i = 0; i< gifCount; i++) { CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL); UIImage *image = [UIImage imageWithCGImage:imageRef]; [frames addObject:image]; CGImageRelease(imageRef); } return frames; } @end