美文网首页
通过CGImageSourceRef播放GIF图

通过CGImageSourceRef播放GIF图

作者: JemmyChen | 来源:发表于2018-05-02 11:54 被阅读0次

通过CGImageSourceRef播放GIF图

-(void)creatGifImage{
    NSData *data =[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1441607086860827" ofType:@"gif"] ];
    //创建图像源
    CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    //获取图像源中的图片数量
    size_t count = CGImageSourceGetCount(imageSource);
    //72张
    NSLog(@"%zu",count);
    UIImage *img;
    NSMutableArray *images = [NSMutableArray new];
    NSTimeInterval duration = 0;
    for (size_t i = 0; i<count; i++) {
        CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, i, NULL);
        if (!image) continue;
        duration +=durationWithSourceAtIndex(imageSource, i);
        [images addObject:[UIImage imageWithCGImage:image]];

        //释放
        CGImageRelease(image);
    }
        if (!duration) duration = 0.1 * count;
        CFRelease(imageSource);
        img = [UIImage animatedImageWithImages:images duration:duration];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
    imageView.frame = CGRectMake(100, 100, 100, 100);
    imageView.image = img;
    [self.view addSubview:imageView];
}

float durationWithSourceAtIndex(CGImageSourceRef source, NSUInteger index) {
    float duration = 0.1f;
    //获取当前帧的属性字典--c类型
    CFDictionaryRef propertiesRef = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    //强转为oc对象
    NSDictionary *properties = (__bridge NSDictionary *)propertiesRef;
    //获取当前帧的gif属性
    NSDictionary *gifProperties = properties[(NSString *)kCGImagePropertyGIFDictionary];
    //获取当前帧的持续时间
    NSNumber *delayTime = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTime) duration = delayTime.floatValue;
    else {
        delayTime = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTime) duration = delayTime.floatValue;
    }
    //释放(由于是c对象,必须手动释放)
    CFRelease(propertiesRef);
    return duration;
}

相关文章

网友评论

      本文标题:通过CGImageSourceRef播放GIF图

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