1. 程式人生 > >iOS gif製作

iOS gif製作

1、建立影象目標

  1. CGImageDestinationRef destination;  

2、建立輸出路徑(儲存的路徑)
  1. /* 
  2.      path 
  3. */

3、建立CFURLRef物件

  1. CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)path, kCFURLPOSIXPathStyle, NO);  

4、通過一個url返回影象目標
  1. destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, mArray
    .count, nil);  

5、設定gif的資訊,播放時隔事件,基本資料和delay事件
  1. NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.18],(NSString *)kCGImagePropertyGIFDelayTime, nil nil] forKey:(NSString *)kCGImagePropertyGIFDictionary];  
  2. //設定gif資訊
  3. NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];  
  4. [dict setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCGImagePropertyGIFImageColorMap];  
  5. [dict setObject:(NSString *)kCGImagePropertyColorModelRGB forKey:(NSString *)kCGImagePropertyColorModel];  
  6. [dict setObject
    :[NSNumber numberWithInt:8] forKey:(NSString *)kCGImagePropertyDepth];  
  7. [dict setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];  
  8. NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:dict forKey:(NSString *)kCGImagePropertyGIFDictionary];  
6、合成gif(把所有圖片遍歷新增到影象目標)
  1. for (UIImage *dImg in mArray)  
  2.   {  
  3.          CGImageDestinationAddImage(destination, dImg.CGImage, (__bridge CFDictionaryRef)frameProperties);  
  4.   }  

7、給gif新增資訊
  1. CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);  

8、寫入gif圖
  1. CGImageDestinationFinalize(destination);  
9、釋放目標影象
  1. CFRelease(destination);