iOS开发中实现显示gif图片的方法

 更新时间:2015年09月26日 10:02:24   作者:一片枫叶  
这篇文章主要介绍了iOS开发中实现显示gif图片的方法,代码基于传统的Objective-C,需要的朋友可以参考下

我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发现他们都没有对Gif中每一帧的显示时常做处理,这样的结果就是整个Gif中每一帧画面都是以固定的速度向前播放,很显然这并不总会符合需求。
 
  于是自己写一个解析Gif的工具类,解决每一帧画面并遵循每一帧所对应的显示时间进行播放。
 
  程序的思路如下:
 
  1、首先使用ImageIO库中的CGImageSource家在Gif文件。
 
  2、通过CGImageSource获取到Gif文件中的总的帧数,以及每一帧的显示时间。
 
  3、通过CAKeyframeAnimation来完成Gif动画的播放。
 
  下面直接上我写的解析和播放Gif的工具类的代码:
 

复制代码 代码如下:

//
//  SvGifView.h
//  SvGifSample
//
//  Created by maple on 3/28/13.
//  Copyright (c) 2013 smileEvday. All rights reserved.
//


#import <UIKit/UIKit.h>

@interface SvGifView : UIView


/*
 * @brief desingated initializer
 */
- (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL;

/*
 * @brief start Gif Animation
 */
- (void)startGif;

/*
 * @brief stop Gif Animation
 */
- (void)stopGif;

/*
 * @brief get frames image(CGImageRef) in Gif
 */
+ (NSArray*)framesInGif:(NSURL*)fileURL;


@end


//
//  SvGifView.m
//  SvGifSample
//
//  Created by maple on 3/28/13.
//  Copyright (c) 2013 smileEvday. All rights reserved.
//

#import "SvGifView.h"
#import <ImageIO/ImageIO.h>
#import <QuartzCore/CoreAnimation.h>

/*
 * @brief resolving gif information
 */
void getFrameInfo(CFURLRef url, NSMutableArray *frames, NSMutableArray *delayTimes, CGFloat *totalTime,CGFloat *gifWidth, CGFloat *gifHeight)
{
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);
   
    // get frame count
    size_t frameCount = CGImageSourceGetCount(gifSource);
    for (size_t i = 0; i < frameCount; ++i) {
        // get each frame
        CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        [frames addObject:(id)frame];
        CGImageRelease(frame);
       
        // get gif info with each frame
        NSDictionary *dict = (NSDictionary*)CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL);
        NSLog(@"kCGImagePropertyGIFDictionary %@", [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);
       
        // get gif size
        if (gifWidth != NULL && gifHeight != NULL) {
            *gifWidth = [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
            *gifHeight = [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
        }
       
        // kCGImagePropertyGIFDictionary中kCGImagePropertyGIFDelayTime,kCGImagePropertyGIFUnclampedDelayTime值是一样的
        NSDictionary *gifDict = [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary];
        [delayTimes addObject:[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime]];
       
        if (totalTime) {
            *totalTime = *totalTime + [[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime] floatValue];
        }
    }
}

@interface SvGifView() {
    NSMutableArray *_frames;
    NSMutableArray *_frameDelayTimes;
   
    CGFloat _totalTime;         // seconds
    CGFloat _width;
    CGFloat _height;
}

@end

@implementation SvGifView


- (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL;
{
    self = [super initWithFrame:CGRectZero];
    if (self) {
       
        _frames = [[NSMutableArray alloc] init];
        _frameDelayTimes = [[NSMutableArray alloc] init];
       
        _width = 0;
        _height = 0;
       
        if (fileURL) {
            getFrameInfo((CFURLRef)fileURL, _frames, _frameDelayTimes, &_totalTime, &_width, &_height);
        }
       
        self.frame = CGRectMake(0, 0, _width, _height);
        self.center = center;
    }
   
    return self;
}

+ (NSArray*)framesInGif:(NSURL *)fileURL
{
    NSMutableArray *frames = [NSMutableArray arrayWithCapacity:3];
    NSMutableArray *delays = [NSMutableArray arrayWithCapacity:3];
   
    getFrameInfo((CFURLRef)fileURL, frames, delays, NULL, NULL, NULL);
   
    return frames;
}

- (void)startGif
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
   
    NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
    CGFloat currentTime = 0;
    int count = _frameDelayTimes.count;
    for (int i = 0; i < count; ++i) {
        [times addObject:[NSNumber numberWithFloat:(currentTime / _totalTime)]];
        currentTime += [[_frameDelayTimes objectAtIndex:i] floatValue];
    }
    [animation setKeyTimes:times];
   
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
    for (int i = 0; i < count; ++i) {
        [images addObject:[_frames objectAtIndex:i]];
    }
   
    [animation setValues:images];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    animation.duration = _totalTime;
    animation.delegate = self;
    animation.repeatCount = 5;
   
    [self.layer addAnimation:animation forKey:@"gifAnimation"];
}

- (void)stopGif
{
    [self.layer removeAllAnimations];
}

// remove contents when animation end
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.layer.contents = nil;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}


@end


  代码很短也比较容易,就不一一解释了。最开始的那个C函数主要就是用来解析Gif的,之所以用C函数是因为我要返回多个信息,而Objective-c只能返回一个参数,而且Objective-c和C语言可以很方便的混合编程。

另外再介绍两种使用UIImageView的方法:

1. 使用UIWebView播放

复制代码 代码如下:

    // 设定位置和大小
    CGRect frame = CGRectMake(50,50,0,0);
    frame.size = [UIImage imageNamed:@"guzhang.gif"].size;
    // 读取gif图片数据
    NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"guzhang" ofType:@"gif"]];
    // view生成
    UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
    webView.userInteractionEnabled = NO;//用户不可交互
    [webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    [self.view addSubview:webView];
    [webView release];

2.将gif图片分解成多张png图片,使用UIImageView播放。
代码如下:

复制代码 代码如下:

 UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    NSArray *gifArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"1"],
                                                  [UIImage imageNamed:@"2"],
                                                  [UIImage imageNamed:@"3"],
                                                  [UIImage imageNamed:@"4"],
                                                  [UIImage imageNamed:@"5"],
                                                  [UIImage imageNamed:@"6"],
                                                  [UIImage imageNamed:@"7"],
                                                  [UIImage imageNamed:@"8"],
                                                  [UIImage imageNamed:@"9"],
                                                  [UIImage imageNamed:@"10"],
                                                  [UIImage imageNamed:@"11"],
                                                  [UIImage imageNamed:@"12"],
                                                  [UIImage imageNamed:@"13"],
                                                  [UIImage imageNamed:@"14"],
                                                  [UIImage imageNamed:@"15"],
                                                  [UIImage imageNamed:@"16"],
                                                  [UIImage imageNamed:@"17"],
                                                  [UIImage imageNamed:@"18"],
                                                  [UIImage imageNamed:@"19"],
                                                  [UIImage imageNamed:@"20"],
                                                  [UIImage imageNamed:@"21"],
                                                  [UIImage imageNamed:@"22"],nil];
    gifImageView.animationImages = gifArray; //动画图片数组
    gifImageView.animationDuration = 5; //执行一次完整动画所需的时长
    gifImageView.animationRepeatCount = 1;  //动画重复次数
    [gifImageView startAnimating];
    [self.view addSubview:gifImageView];
    [gifImageView release];

注意:这个方法,如果gif动画每桢间的时间间隔不同,不能达到此效果。

相关文章

  • iOS应用程序中通过dispatch队列控制线程执行的方法

    iOS应用程序中通过dispatch队列控制线程执行的方法

    Grand Central Dispatch简称(GCD)是苹果公司开发的技术,以优化的应用程序支持多核心处理器和其他的对称多处理系统的系统,iOS应用程序中通过dispatch队列控制线程执行则是以并发来达到多核优化的重要途径.
    2016-05-05
  • iOS获取短信验证码倒计时的两种实现方法

    iOS获取短信验证码倒计时的两种实现方法

    本篇文章主要介绍了iOS获取短信验证码倒计时的两种实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • 查看iOS已上架App的Crash信息定位、应对处理方式的实例

    查看iOS已上架App的Crash信息定位、应对处理方式的实例

    下面小编就为大家带来一篇查看iOS已上架App的Crash信息定位、应对处理方式的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • IOS使用UICollectionView实现无限轮播效果

    IOS使用UICollectionView实现无限轮播效果

    这篇文章主要为大家详细介绍了IOS使用UICollectionView实现无限轮播效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-03-03
  • iOS开发删除storyboard步骤详解

    iOS开发删除storyboard步骤详解

    这篇文章主要为大家介绍了iOS系列学习之删除storyboard步骤详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • 详解iOS开发中UItableview控件的数据刷新功能的实现

    详解iOS开发中UItableview控件的数据刷新功能的实现

    这篇文章主要介绍了详解iOS开发中UItableview控件的数据刷新功能的实现,代码基于传统的Objective-C,需要的朋友可以参考下
    2015-12-12
  • iOS中UIRefreshControl的基本使用详解

    iOS中UIRefreshControl的基本使用详解

    最近在应用中用到UIRefreshControl,觉着有必要给大家总结介绍一下这个控件,所以下面这篇文章主要给大家介绍了关于iOS中UIRefreshControl的基本使用的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-04-04
  • iOS实现百度地图拖拽后更新位置以及反编码

    iOS实现百度地图拖拽后更新位置以及反编码

    百度地图已经开放了地图API,大家可以很方便的调用地图中的相应数据,并完成各项个性化的展示,下面这篇文章主要给大家介绍了关于iOS如何实现百度地图拖拽后更新位置以及反编码的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-12-12
  • iOS开发多线程下全局变量赋值崩溃原理详解

    iOS开发多线程下全局变量赋值崩溃原理详解

    这篇文章主要为大家介绍了iOS开发多线程下全局变量赋值崩溃原理详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • iOS实现图片保存与搜索功能

    iOS实现图片保存与搜索功能

    这篇文章主要介绍了iOS实现图片保存与搜索功能的相关资料,需要的朋友可以参考下
    2016-02-02

最新评论