UIImageGIFRepresentation

使用[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;
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容