NSTimer实现Gif动画播放

一年又见底了,一年收集的资料文档,趁现在的空闲会陆续的整理出来。。。

<一、GIF的动画播放>

实现动画Gif的播放需要引入

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
这些头文件,以下是代码实现

@interface GifLoadingView()
@property (nonatomic, assign) size_t index; // 当前的帧数
@property (nonatomic, assign) size_t count; // 一共多少帧
@property (nonatomic, strong) NSTimer *gifTimer; // 定时器
@property (nonatomic, assign) CGImageSourceRef gifSource; // 图片资源
@property (nonatomic, strong) NSDictionary *gifDic; // gif动画属性

 

// 开始动画

- (void)beginAnimation;
@end

@implementation GifLoadingView

- (void)createGif
{
  NSDictionary *gifLoopCount = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];
  self.gifDic = [NSDictionary dictionaryWithObject:gifLoopCount forKey:(NSString *)kCGImagePropertyGIFDictionary];

  // 加载本地资源
  NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"loading" ofType:@"gif"]];
  self.gifSource = CGImageSourceCreateWithData((CFDataRef)self.gifSource, (CFDictionaryRef)self.gifDic);
  self.count = CGImageSourceGetCount(self.gifSource);

  // 获取gif的第一张图片
  CGImageRef imageRef = CGImageSourceCreateImageAtIndex(self.gifSource, self.index, (CFDictionaryRef)self.gifDic);
  self.layer.contents = (__bridge id)imageRef;

  // 使用完后需要手动释放
  CFRelease(imageRef);
}

 

- (void)beginAnimation
{
  self.gifTimer = [NSTimer timerWithTimeInterval:0.02 target:self selector:@selector(startLoading) userInfo:nil repeats:YES];
  [[NSRunLoop mainRunLoop] addTimer:self.gifTimer forMode:NSDefaultRunLoopMode];
}

 

- (void)startLoading
{
  self.index ++;
  self.index = self.index % self.count;

  if (self.index % self.count == 0) {
    [self stopGif];
    return;
}

  CGImageRef ref = CGImageSourceCreateImageAtIndex(self.gif, self.index, (CFDictionaryRef)self.gifDic);
  self.layer.contents = (__bridge id)ref;
  CFRelease(ref);
}

 

// 取消定时器

- (void)stopGif
{
  [self.gifTimer invalidate];
  self.gifTimer = nil;
}

 

- (void)dealloc
{
  CFRelease(self.gifSource);
}


@end

 

 

最后添加一张关于ImageIO的全家福

参考资料:http://www.haogongju.net/art/1328578

转载于:https://www.cnblogs.com/sparrows/p/8316834.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值