iOS 播放GIF动态图片!!!!!

时间:2021-03-09 18:07:38

//////////////////////////////////////////////////////////////////////////////////////////

//
//  ViewController.m
//  播放动态图片
//

#import "ViewController.h"
#import "GifView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//第一种 用UIImageView中的动画数组播放动画
    [self showGifImageMethodOne];
//第二种 用UIWebView显示
    [self showGifImageMethodTwo];
//第三种 用第三方GifView显示本地图片
    [self showGifImageMethodThree];
//用第三方显示从网络获取的动态图片
    [self showGifImageMethodFour];
}

#pragma mark 播放动态图片方式1 UIImageView
-(void)showGifImageMethodOne {
//第一种 用UIImageView中的动画数组播放动画
    //创建UIImageView,添加到界面
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
    [self.view addSubview:imageView];
    //创建一个数组,数组中按顺序添加要播放的图片(图片为静态的图片)
    NSMutableArray *imgArray = [NSMutableArray array];
    for (int i=1; i<7; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"clock%02d.png",i]];
        [imgArray addObject:image];
    }
    //把存有UIImage的数组赋给动画图片数组
    imageView.animationImages = imgArray;
    //设置执行一次完整动画的时长
    imageView.animationDuration = 6*0.15;
    //动画重复次数 (0为重复播放)
    imageView.animationRepeatCount = 0;
    //开始播放动画
    [imageView startAnimating];
    //停止播放动画  - (void)stopAnimating;
    //判断是否正在执行动画  - (BOOL)isAnimating;
}

#pragma mark 播放动态图片方式2 UIWebView
-(void)showGifImageMethodTwo {
//第二种 用UIWebView显示
    //得到图片的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"happy" ofType:@"gif"];
    //将图片转为NSData
    NSData *gifData = [NSData dataWithContentsOfFile:path];
    //创建一个webView,添加到界面
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 150, 200, 200)];
    [self.view addSubview:webView];
    //自动调整尺寸
    webView.scalesPageToFit = YES;
    //禁止滚动
    webView.scrollView.scrollEnabled = NO;
    //设置透明效果
    webView.backgroundColor = [UIColor clearColor];
    webView.opaque = 0;
    //加载数据
    [webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
}

#pragma mark 播放动态图片方式3 第三方显示本地动态图片
-(void)showGifImageMethodThree {
//方式一
    //将图片转为NSData数据
    NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bird" ofType:@"gif"]];
    //创建一个第三方的View显示图片
    GifView *dataView = [[GifView alloc] initWithFrame:CGRectMake(0, 300, 200, 100) data:localData];
    [self.view addSubview:dataView];
//方式二
    //得到图片的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"gif"];
    GifView *dataView2 = [[GifView alloc] initWithFrame:CGRectMake(200, 300, 150, 100) filePath:path];
    [self.view addSubview:dataView2];
}

#pragma mark 播放动态图片方式3 第三方显示从网络获取的动态图片
-(void)showGifImageMethodFour {
    // 网络图片
    NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic19.nipic.com/20120222/8072717_124734762000_2.gif"]];
    //创建一个第三方的View显示图片
    GifView *dataViewWeb = [[GifView alloc] initWithFrame:CGRectMake(20, 420, 280, 100) data:urlData];
    [self.view addSubview:dataViewWeb];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

//////////////////////////////////////////////////////////////////////////////////////////

//
//  GifView.h
//  GIFViewer
//

#import <UIKit/UIKit.h>
#import <ImageIO/ImageIO.h>

@interface GifView : UIView {
    CGImageSourceRef gif;
    NSDictionary *gifProperties;
    size_t index;
    size_t count;
    NSTimer *timer;
}

- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath;

- (id)initWithFrame:(CGRect)frame data:(NSData *)_data;

@end

//
//  GifView.m
//  GIFViewer
//

#import "GifView.h"
#import <QuartzCore/QuartzCore.h>

@implementation GifView

- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath {
    self = [super initWithFrame:frame];
    if (self) {
        gifProperties = [[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount]
                                                     forKey:(NSString *)kCGImagePropertyGIFDictionary] retain];
        gif = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:_filePath], (CFDictionaryRef)gifProperties);
        count =CGImageSourceGetCount(gif);
        timer = [NSTimer scheduledTimerWithTimeInterval:0.12 target:self selector:@selector(play) userInfo:nil repeats:YES];
        [timer fire];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame data:(NSData *)_data{
    self = [super initWithFrame:frame];
    if (self && _data) {
        gifProperties = [[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount]
                                                     forKey:(NSString *)kCGImagePropertyGIFDictionary] retain];
       gif = CGImageSourceCreateWithData((CFDataRef)_data, (CFDictionaryRef)gifProperties);
        count =CGImageSourceGetCount(gif);
        timer = [NSTimer scheduledTimerWithTimeInterval:0.12 target:self selector:@selector(play) userInfo:nil repeats:YES];
        [timer fire];
    }
    return self;
}

-(void)play {
    index ++;
    index = index % count;
    CGImageRef ref = CGImageSourceCreateImageAtIndex(gif, index, (CFDictionaryRef)gifProperties);
    self.layer.contents = (id)ref;
    CFRelease(ref);
}

-(void)removeFromSuperview {
    NSLog(@"removeFromSuperview");
    [timer invalidate];
    timer = nil;
    [super removeFromSuperview];
}
- (void)dealloc {
    NSLog(@"dealloc");
    CFRelease(gif);
    [gifProperties release];
    [super dealloc];
}

@end

//两种加载GIF动态图方式的优劣

//经过测试,从加载速度来说,通过UIImageView类别加载的方式更加快速,UIWebView的方式加载时间会稍长,但是从性能上来比较,WebView的方式性能更优,播放的GIF动态图更加流畅,在开发中可以根据需求,适当比较.例如虽然WebView加载的方式性能更好,但是在许多情况下,原生的UIImageView能够更加*的让开发者扩展.