欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS生成gif图片

程序员文章站 2022-03-25 09:53:49
...

前言

记录一下最新遇到的需求,就是在播放的过程中生成gif表情包,这里我选择了iOS系统库CGImageDestinationRef

使用教程

创建CGImageDestinationRef

_url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)_exportURL, kCFURLPOSIXPathStyle, false);
// 300表示预计需要插入的图片,这个值如果小于预设值,CGImageDestinationRef会缓存对应的图片到cache里面,导致存在内存问题。因此,这个值最好设置的比你想插入的值更大一点。
_destination = CGImageDestinationCreateWithURL(_url, kUTTypeGIF, 300, NULL);

配置CGImageDestinationRef

NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:2];
[dict setObject:[NSNumber numberWithBool:YES] forKey:(NSString*)kCGImagePropertyGIFHasGlobalColorMap];
[dict setObject:[NSNumber numberWithInt:8] forKey:(NSString*)kCGImagePropertyDepth];
// loop表示循环的次数,0表示无限循环,其他表示循环的次数
[dict setObject:[NSNumber numberWithInt:_loop] forKey:(NSString*)kCGImagePropertyGIFLoopCount];
    
NSDictionary* property = [NSDictionary dictionaryWithObject:dict forKey:(NSString *)kCGImagePropertyGIFDictionary];
CGImageDestinationSetProperties(_destination, (__bridge CFDictionaryRef)property);

添加图片到CGImageDestinationRef

// 指示每一帧之间的duration,单位为秒。
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:0.1],(NSString *)kCGImagePropertyGIFDelayTime, nil];
NSDictionary *properties = [NSDictionary dictionaryWithObject:dict forKey:(NSString *)kCGImagePropertyGIFDictionary];
    
CGImageDestinationAddImage(_destination, cgimage, (__bridge CFDictionaryRef)properties);

结束生成gif图片

CGImageDestinationFinalize(_destination);