NSTimer實現Gif動畫播放

一年又見底了,一年收集的資料文檔,趁如今的空閒會陸續的整理出來。。。oop

<1、GIF的動畫播放>動畫

實現動畫Gif的播放須要引入atom

#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>
這些頭文件,如下是代碼實現

spa

@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動畫屬性.net

 

// 開始動畫blog

- (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);get

  // 獲取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

相關文章
相關標籤/搜索