美文网首页
UIImageGIFRepresentation

UIImageGIFRepresentation

作者: 梓华 | 来源:发表于2020-12-03 17:08 被阅读0次

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

相关文章

网友评论

      本文标题:UIImageGIFRepresentation

      本文链接:https://www.haomeiwen.com/subject/jlzmwktx.html