我使用以下方法生成gif。
-(void)makeAnimatedGif:(NSArray *)imgArray {
__block NSString *fileName = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do background work
NSUInteger kFrameCount = imgArray.count;
NSDictionary *fileProperties = @{
(__bridge id)kCGImagePropertyGIFDictionary: @{
(__bridge id)kCGImagePropertyGIFLoopCount: @0, // 0 means loop forever
}
};
NSDictionary *frameProperties = @{
(__bridge id)kCGImagePropertyGIFDictionary: @{
(__bridge id)kCGImagePropertyGIFDelayTime: @0.02f, // a float (not double!) in seconds, rounded to centiseconds in the GIF data
}
};
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF, kFrameCount, NULL);
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)fileProperties);
for (NSUInteger i = 0; i < kFrameCount; i++) {
@autoreleasepool {
UIImage *image =[imgArray objectAtIndex:i]; //Here is the change
if (image.CGImage) {
CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
}
}
}
if (!CGImageDestinationFinalize(destination)) {
NSLog(@"failed to finalize image destination");
}
dispatch_async(dispatch_get_main_queue(), ^{
//Update UI
CFRelease(destination);
[self manageGifWithUrl:fileURL];
});
});
}
我的gif问题是尺寸非常大。生成的gif的大小范围从40MB到90MB。我无法找到任何解决方案。
我的imgArray包含180张图片。有没有解决这个问题?