使用[UIImage animatedImageWithImages函数,一组序列图返回一个动图image,[UIImage UIImageGIFRepresentation:image 返回data,data另存为 可以保存为GIF图
+ (NSData *)UIImageGIFRepresentation:(UIImage *)image duration:(NSTimeInterval)duration repeatCount:(NSInteger)repeatCount
{
NSArray<UIImage *> *images = image.images;
if(images == nil)
{
return nil;
}
NSInteger frameCount = images.count;
CGFloat gifDuration = duration <= 0.0 ? (image.duration / frameCount) : (duration / frameCount);
NSDictionary *framePropertiesValue = [[NSDictionary alloc] initWithObjectsAndKeys:(__bridge NSString *)kCGImagePropertyGIFDelayTime, @(gifDuration), nil];
NSDictionary *frameProperties = [[NSDictionary alloc] initWithObjectsAndKeys:(__bridge NSString *)kCGImagePropertyGIFDictionary, framePropertiesValue, nil];
NSDictionary *imagePropertiesValue = [[NSDictionary alloc] initWithObjectsAndKeys:(__bridge NSString *)kCGImagePropertyGIFLoopCount, @(repeatCount), nil];
NSDictionary *imageProperties = [[NSDictionary alloc] initWithObjectsAndKeys:(__bridge NSString *)kCGImagePropertyGIFDictionary, imagePropertiesValue, nil];
NSMutableData *data = [[NSMutableData alloc] init];
CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)data, kUTTypeGIF, frameCount, nil);
CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)imageProperties);
for(UIImage *image in images)
{
CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
}
if(CGImageDestinationFinalize(destination))
{
return [NSData dataWithData:data];
}
else
{
return nil;
}
}
网友评论