其实网上GitHub有很多第三方的,但是用起来比较麻烦,这里介绍最简单的一种方式,自己就可以实现,(点击按钮开始播放动态图)
1,集成SDWebImage之后,引入头文件#import "UIImage+GIF.h"
2.初始化按钮,(loadingImageView是定义的全局的UIImageView,自己定义下)
self.loadingImageView= [[UIImageView alloc]init]; UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 100, 50, 20)]; btn.backgroundColor=[UIColor redColor]; [self.view addSubview:btn]; [btn addTarget:self action:@selector(initLoadingImageView) forControlEvents:UIControlEventTouchUpInside];
3.点击按钮就可以实现了,非常简单
- (void)initLoadingImageView { NSString *name = @"图片的名字.gif"; NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil]; NSData *imageData = [NSData dataWithContentsOfFile:filePath]; if (!self.loadingImageView) { self.loadingImageView = [[UIImageView alloc]init]; } self.loadingImageView.backgroundColor = [UIColor clearColor]; self.loadingImageView.image = [UIImage sd_animatedGIFWithData:imageData]; //这里可以修改要实现播放的gif的frame self.loadingImageView.frame = CGRectMake(0, 100, 200, 100); [self.view addSubview:self.loadingImageView]; [self.view bringSubviewToFront:self.loadingImageView]; }
如果想实现gif图片的暂停和继续播放的功能加入以下两个方法就可以了
1.首先再viewDidLoad加入这个(player是CALayer类型的,定义为全局的)
// 设置imageView的layer player = self.loadingImageView.layer;
2.实现这两个方法,需要用哪个就点击哪个直接把player传过去就可以了
//暂停gif的方法 -(void)pauseLayer:(CALayer*)layer { CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil]; layer.speed = 0.0; layer.timeOffset = pausedTime; } //继续gif的方法 -(void)resumeLayer:(CALayer*)layer { CFTimeInterval pausedTime = [layer timeOffset]; layer.speed = 1.0; layer.timeOffset = 0.0; layer.beginTime = 0.0; CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime; layer.beginTime = timeSincePause; }