Last active
November 12, 2022 15:25
-
-
Save maddiesch/4727403 to your computer and use it in GitHub Desktop.
Create an animated UIImage from .gif data.
This file contains 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
+ (UIImage *)imageFromGifData:(NSData *)data { | |
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFTypeRef)data, NULL); | |
if (!source) { | |
return nil; | |
} | |
CFDictionaryRef dict = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL); | |
NSDictionary *metadata = (__bridge NSDictionary *)dict; | |
CGFloat offset = 0.0; | |
if (metadata[@"{GIF}"]) { | |
NSDictionary *meta = metadata[@"{GIF}"]; | |
offset = [meta[@"DelayTime"] floatValue]; | |
} | |
CFRelease(dict); | |
int64_t count = CGImageSourceGetCount(source); | |
NSMutableArray *images = [NSMutableArray arrayWithCapacity:count]; | |
for (int64_t i = 0; i < count; i++) { | |
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, i, NULL); | |
if (cgImage == nil) { | |
CFRelease(source); | |
return nil; | |
} | |
[images addObject:[UIImage imageWithCGImage:cgImage]]; | |
CGImageRelease(cgImage); | |
} | |
CFRelease(source); | |
return [UIImage animatedImageWithImages:images duration:count * offset]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to add
To the file.