美文网首页iOS日常须知
iOS加载网络gif或者本地gif图片

iOS加载网络gif或者本地gif图片

作者: charlotte2018 | 来源:发表于2017-04-10 09:59 被阅读318次

有时候需要load网络的链接,加载gif图片。上代码。

#import "ViewController.h"
#import <ImageIO/ImageIO.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlString = @"http://www.wyzu.cn/data/uploadfile/200803/20080328122630185.gif";
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.image = [self getGitImageWithData:data];
    [self.view addSubview:imageView];
    
    NSLog(@"%@",data);
    
}

- (UIImage *)getGitImageWithData:(NSData* )data
{
    CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    size_t count = CGImageSourceGetCount(imageSource);
    NSMutableArray *images = [NSMutableArray array];
    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);
    return [UIImage animatedImageWithImages:images duration:duration];
    
}

#pragma mark 获取每一帧图片的时长
float durationWithSourceAtIndex(CGImageSourceRef source, NSUInteger index) {
    float duration = 0.1f;
    CFDictionaryRef propertiesRef = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *properties = (__bridge NSDictionary *)propertiesRef;
    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;
    }
    CFRelease(propertiesRef);
    return duration;
}

- (UIImage *)getLocalGifWithImageNamed:(NSString *)imageName
{
    if (![imageName hasSuffix:@".gif"]) {
        imageName = [imageName stringByAppendingString:@".gif"];
    }
    
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:nil];
    NSData *data = [NSData dataWithContentsOfFile:imagePath];
    return  [self getGitImageWithData:data];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

相关文章

网友评论

    本文标题:iOS加载网络gif或者本地gif图片

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