有时候需要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