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

iOS开发中实现显示gif图片的方法,第1张

概述我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发现他们都没有对Gif中每一帧的显示时常做处理,这样的结果就是整个Gif中每一帧画面都是以固定的速度向前播放,很显然这

我们知道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,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,_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);
   
    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);
    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中播放gif动态图的方法iOS Gif图片展示N种方式(原生+第三方)iOS之加载Gif图片的方法 总结

以上是内存溢出为你收集整理的iOS开发中实现显示gif图片的方法全部内容,希望文章能够帮你解决iOS开发中实现显示gif图片的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1142731.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存