用于播放 GIF 图片的代码
1.使用webView加载
-(void)way1
{
// 设定位置和大小
CGRect frame ;
frame.size = [UIImage imageNamed:@"2.gif"].size;
// 读取gif图片数据
NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"2" ofType:@"gif"]];
// view生成
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
webView.backgroundColor =[UIColor blackColor];
webView.userInteractionEnabled = NO;//用户不可交互
[webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
[self.view addSubview:webView];
//[webView release];
}
第二种方法(将gif解析成一个包含n张图片的数组,在使用帧动画将它播放出来)
#import "ViewController.h"
#import <ImageIO/ImageIO.h> //CGImageSource对图像数据读取任务的抽象
#import <QuartzCore/CoreAnimation.h>//帧动画
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"2" withExtension:@"gif"];
NSData *date = [NSData dataWithContentsOfURL:fileUrl];
[self animationWithImageArr:[self praseGIFDataToImageArray:date]];
}
//将gif图像解析成一个包含UIImage对象的数组
- (NSMutableArray *)praseGIFDataToImageArray:(NSData *)data;
{
NSMutableArray *images = [[NSMutableArray alloc] init];
CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)data, NULL);
if (src) {
size_t l = CGImageSourceGetCount(src);
images = [NSMutableArray arrayWithCapacity:l];
for (size_t i = 0; i < l; i++) {
CGImageRef imgRef = CGImageSourceCreateImageAtIndex(src, i, NULL);
UIImage *aImage = [[UIImage alloc]initWithCGImage:imgRef];
[images addObject:aImage];
}
CFRelease(src);
}
return images;
}
//将图像重新变成一个动画(帧动画),这里可以自己设置动画的间隔时间
-(void)animationWithImageArr:(NSMutableArray *)imagesArray
{
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
NSArray *gifArray = [imagesArray mutableCopy];
gifImageView.animationImages = gifArray; //动画图片数组
gifImageView.animationDuration = 0.2; //执行一次完整动画所需的时长
gifImageView.animationRepeatCount = MAXFLOAT; //动画重复次数
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
}
@end