/** 1. 數據獲取 2. 建立Gif文件 3. 配置Gif屬性 4. 單幀添加到gif */
github地址: https://github.com/mancongiOS/UIImage.gitgit
導入: github
#import <ImageIO/ImageIO.h> #import <MobileCoreServices/MobileCoreServices.h>
實現: oop
// 1. 獲取數據 NSMutableArray * imageArrayM = [NSMutableArray arrayWithCapacity:0]; [imageArrayM addObject:[UIImage imageNamed:@"1.png"]]; [imageArrayM addObject:[UIImage imageNamed:@"2"]]; [imageArrayM addObject:[UIImage imageNamed:@"3"]]; [imageArrayM addObject:[UIImage imageNamed:@"4"]]; [imageArrayM addObject:[UIImage imageNamed:@"5"]]; [imageArrayM addObject:[UIImage imageNamed:@"6"]]; [imageArrayM addObject:[UIImage imageNamed:@"7"]]; [imageArrayM addObject:[UIImage imageNamed:@"8"]]; // 2. 建立Gif文件 NSArray * document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentStr = [document objectAtIndex:0]; NSFileManager * fileManager = [NSFileManager defaultManager]; NSString * textDic = [documentStr stringByAppendingString:@"/gif"]; [fileManager createDirectoryAtPath:textDic withIntermediateDirectories:YES attributes:nil error:nil]; NSString * path = [textDic stringByAppendingString:@"test1.gif"]; NSLog(@"path: %@",path); // 3. 配置gif屬性 CGImageDestinationRef destion; // 將path映射成url對象 CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLPOSIXPathStyle, false); destion = CGImageDestinationCreateWithURL(url, kUTTypeGIF, imageArrayM.count, NULL); NSMutableDictionary * dictM = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.3],(NSString *)kCGImagePropertyGIFDelayTime, nil]; NSDictionary * frameDic = [NSDictionary dictionaryWithObject:dictM forKey:(NSString *)kCGImagePropertyGIFDelayTime]; NSMutableDictionary * gifParaDict = [NSMutableDictionary dictionaryWithCapacity:2]; // 設置顏色 [gifParaDict setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap]; // 設置模式 [gifParaDict setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel]; // 設置顏色深度 [gifParaDict setObject:[NSNumber numberWithInt:8] forKey:(NSString *)kCGImagePropertyDepth]; // 是否能夠重複播放 [gifParaDict setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount]; NSDictionary * gifProperty = [NSDictionary dictionaryWithObject:gifParaDict forKey:(NSString *)kCGImagePropertyGIFDictionary]; // 單幀添加到gif for (UIImage * dImage in imageArrayM) { CGImageDestinationAddImage(destion, dImage.CGImage, (__bridge CFDictionaryRef)frameDic); } CGImageDestinationSetProperties(destion, (__bridge CFDictionaryRef)gifProperty); CGImageDestinationFinalize(destion); CFRelease(url); CFRelease(destion);