iOS開(kāi)發(fā)中實(shí)現(xiàn)顯示gif圖片的方法
我們知道Gif是由一陣陣畫面組成的,而且每一幀畫面播放的時(shí)常可能會(huì)不相等,觀察上面兩個(gè)例子,發(fā)現(xiàn)他們都沒(méi)有對(duì)Gif中每一幀的顯示時(shí)常做處理,這樣的結(jié)果就是整個(gè)Gif中每一幀畫面都是以固定的速度向前播放,很顯然這并不總會(huì)符合需求。
于是自己寫一個(gè)解析Gif的工具類,解決每一幀畫面并遵循每一幀所對(duì)應(yīng)的顯示時(shí)間進(jìn)行播放。
程序的思路如下:
1、首先使用ImageIO庫(kù)中的CGImageSource家在Gif文件。
2、通過(guò)CGImageSource獲取到Gif文件中的總的幀數(shù),以及每一幀的顯示時(shí)間。
3、通過(guò)CAKeyframeAnimation來(lái)完成Gif動(dòng)畫的播放。
下面直接上我寫的解析和播放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
代碼很短也比較容易,就不一一解釋了。最開(kāi)始的那個(gè)C函數(shù)主要就是用來(lái)解析Gif的,之所以用C函數(shù)是因?yàn)槲乙祷囟鄠€(gè)信息,而Objective-c只能返回一個(gè)參數(shù),而且Objective-c和C語(yǔ)言可以很方便的混合編程。
另外再介紹兩種使用UIImageView的方法:
1. 使用UIWebView播放
// 設(shè)定位置和大小
CGRect frame = CGRectMake(50,50,0,0);
frame.size = [UIImage imageNamed:@"guzhang.gif"].size;
// 讀取gif圖片數(shù)據(jù)
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; //動(dòng)畫圖片數(shù)組
gifImageView.animationDuration = 5; //執(zhí)行一次完整動(dòng)畫所需的時(shí)長(zhǎng)
gifImageView.animationRepeatCount = 1; //動(dòng)畫重復(fù)次數(shù)
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
[gifImageView release];
注意:這個(gè)方法,如果gif動(dòng)畫每楨間的時(shí)間間隔不同,不能達(dá)到此效果。
相關(guān)文章
iOS推送增加右側(cè)顯示圖Service Extension
這篇文章主要為大家介紹了iOS推送增加右側(cè)顯示圖Service Extension,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10淺談強(qiáng)大易用支持URL Rewrite的iOS路由庫(kù)FFRouter
FRouter 是 iOS 中一個(gè)強(qiáng)大且易用的 URL 路由庫(kù),支持 URL Rewrite,基于匹配查找 URL,效率高。非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-10-10IOS 單擊手勢(shì)的添加實(shí)現(xiàn)代碼
這篇文章主要介紹了IOS 單擊手勢(shì)的添加實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05iOS給圖片添加濾鏡&使用openGLES動(dòng)態(tài)渲染圖片詳解及實(shí)例
這篇文章主要介紹了iOS給圖片添加濾鏡&使用openGLES動(dòng)態(tài)渲染圖片詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2016-10-10iOS下PDF文件的瀏覽和涂鴉效果的簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要介紹了iOS下PDF文件的瀏覽和涂鴉效果的簡(jiǎn)單實(shí)現(xiàn),代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-10-10iOS開(kāi)發(fā)中UIPopoverController的使用詳解
這篇文章主要介紹了iOS開(kāi)發(fā)中UIPopoverController的使用,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11講解iOS開(kāi)發(fā)中UITableView列表設(shè)計(jì)的基本要點(diǎn)
這篇文章主要介紹了講解iOS開(kāi)發(fā)中UITableView列表設(shè)計(jì)的基本要點(diǎn),其中對(duì)列表行操作的常用操作舉例是iOS開(kāi)發(fā)中經(jīng)常用到的基礎(chǔ),需要的朋友可以參考下2016-01-01iOS開(kāi)發(fā)--仿新聞首頁(yè)效果WMPageController的使用詳解
這篇文章主要介紹了iOS開(kāi)發(fā)--仿新聞首頁(yè)效果WMPageController的使用詳解,詳解的介紹了iOS開(kāi)發(fā)中第三方庫(kù)WMPageController控件的使用方法,有需要的可以了解下。2016-11-11