在 iOS 中进行有效的内存优化 GIF 播放的库。这个库不会一次性准备所有帧,而是在活帧中更新。因此,在这种方式下,内存使用量大大降低,但 CPU 使用量增加(因为 GIF 解码)。
将以下文件复制到您的项目中:AnimatedGif.h
,AnimatedGif.m
,UIImageView+AnimatedGif.h
,UIImageView+AnimatedGif.m
。
创建带有 GIF 内容的图像视图
AnimatedGif * gif = [AnimatedGif getAnimationForGifAtUrl:[NSURL URLWithString:@"http://s6.pikabu.ru/post_img/2014/04/07/6/1396854652_1659897712.gif"]];
UIImageView * newImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 300, 200)];
[newImageView setAnimatedGif:gif];
[gif setLoadingProgressBlock:^(AnimatedGif *obj, CGFloat progress) {
progressView.progress = progress;
}];
[gif setWillShowFrameBlock:^(AnimatedGif *obj, UIImage *img) {
progressView.hidden = YES;
//... Do stuff
}];
[gif start];
[self.view addSubview:newImageView];
...
//Another way
NSData * animationData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1.gif" ofType:nil]];
AnimatedGif * animation = [AnimatedGif getAnimationForGifWithData:animationData];
UIImageView * newImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 300, 200)];
[newImageView setAnimatedGif:animation startImmediately:YES];
[self.view addSubview:newImageView];
要管理 GIF 图像视图,您可以设置以下事件:AnimatedGifDidStartLoadingingEvent
,AnimatedGifDidFinishLoadingingEvent
。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animatedGifDidStart:) name:AnimatedGifDidStartLoadingingEvent object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animatedGifDidFinish:) name:AnimatedGifDidFinishLoadingingEvent object:nil];
...
-(void)animatedGifDidStart:(NSNotification*) notify {
AnimatedGif * object = notify.object;
NSLog(@"Url will be loaded: %@", object.url);
}
-(void)animatedGifDidFinish:(NSNotification*) notify {
AnimatedGif * object = notify.object;
NSLog(@"Url is loaded: %@", object.url);
...
}
您还可以使用 block setWillShowFrameBlock
。
如有任何疑问,请参阅示例。
由 Stijn Spijker 创建
由 Roman Truba 升级
MIT 许可证 (MIT)
版权所有 (c) 2014 Roman Truba
特此授予任何获得此软件及其相关文档副本(以下简称“软件”)的人自由使用的许可,不受限制,包括但不限于使用、复制、修改、合并、发布、分发、特许经营和/或销售软件副本的权利,并允许软件收件人处理该软件,但应遵守以下条件
上述版权声明和本许可声明应包含在软件的所有副本或主要部分中。
本软件按“现状”提供,不提供任何明示或暗示的保证,包括但不限于商销性、特定目的适用性和非侵权性保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任负责,无论是由于合同、侵权或其他行为,从软件中产生的、与软件的使用或其他方式相关的损害。