Created
October 4, 2013 15:17
-
-
Save perlmunger/6827665 to your computer and use it in GitHub Desktop.
Write Animated GIF Image with Completion Block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (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