Skip to content

Instantly share code, notes, and snippets.

@perlmunger
Created October 4, 2013 15:17
Show Gist options
  • Save perlmunger/6827665 to your computer and use it in GitHub Desktop.
Save perlmunger/6827665 to your computer and use it in GitHub Desktop.
Write Animated GIF Image with Completion Block
+ (void)writeAnimatedGIFToPath:(NSURL*)path withImages:(NSArray*)images duration:(CGFloat)duration completionBlock:(dispatch_block_t)completionBlock;
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *fileProperties = @{
(__bridge id)kCGImagePropertyGIFDictionary: @{
(__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
}
};
NSDictionary *frameProperties = @{
(__bridge id)kCGImagePropertyGIFDictionary: @{
(__bridge id)kCGImagePropertyGIFDelayTime:@(duration / (CGFloat)[images count]),
}
};
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)path, kUTTypeGIF, [images count], NULL);
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileProperties);
for (id image in images) {
@autoreleasepool {
if ([image isKindOfClass:[UIImage class]]) {
CGImageDestinationAddImage(destination, [image CGImage], (__bridge CFDictionaryRef)frameProperties);
} else {
CGImageDestinationAddImage(destination, (__bridge CGImageRef)image, (__bridge CFDictionaryRef)frameProperties);
}
}
}
if (!CGImageDestinationFinalize(destination)) {
NSLog(@"failed to finalize image destination");
}
CFRelease(destination);
NSLog(@"url=%@", path);
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), completionBlock);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment