Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁。但是iOS竟然没有现成的支持加载和播放Gif的类。
简单地汇总了一下,大概有以下几种方法:
<强>一、加载本地Gif文件强>
<强> 1,使用UIWebView 强>
//读取gif图片数据 UIWebView * webView=[[UIWebView alloc] initWithFrame: CGRectMake (0, 0200200)); (自我。视图addSubview webView):; NSString *路径=[[NSBundle mainBundle] pathForResource: @减低:“001”@“gif”);/* NSData *数据=[NSData dataWithContentsOfFile路径):; 使用loadData: MIMEType: textEncodingName:则有警告 [webView loadData:数据MIMEType: @“图像/gif”textEncodingName: nil baseURL: nil); */NSURL * url=[NSURL URLWithString路径):; [webView loadRequest: [NSURLRequest requestWithURL: url]]; >之前但是使用UIWebView的弊端在于,不能设置Gif动画的播放时间。
<强> 2,将Gif拆分成多张图片,使用UIImageView播放强>
最好把所需要的Gif图片打包到包文件内,如下图所示
- (NSArray *) animationImages { NSFileManager * fielM=[NSFileManager defaultManager]; NSString *路径=[[NSBundle mainBundle] pathForResource: @减低:“加载”@“束”); NSArray *数组=[fielM contentsOfDirectoryAtPath:路径错误:nil); NSMutableArray * imagesArr=[NSMutableArray数组); 在数组(NSString *的名字){ 界面图像*图像=[界面图像imageNamed: [(@“Loading.bundle”) stringByAppendingPathComponent:名称]]; 如果(图片){ [imagesArr addObject:图像); } } 返回imagesArr; } - (void) viewDidLoad { (超级viewDidLoad); UIImageView * gifImageView=[[UIImageView alloc] initWithFrame:框架); gifImageView。animationImages=(自我animationImages);//获取Gif图片列表 gifImageView。animationDuration=5;//执行一次完整动画所需的时长 gifImageView。animationRepeatCount=0;//动画重复次数 [gifImageView startAnimating]; (自我。视图addSubview gifImageView):; } >之前
<强> 3,使用SDWebImage 强>
但是很遗憾,SDWebImage的sd_setImageWithURL: placeholderImage:这个方法是不能播放本地Gif的,它只能显示Gif的第一张图片而已。所以,此方法行不通
UIImageView * gifImageView=[[UIImageView alloc] initWithFrame:框架); [gifImageView sd_setImageWithURL: nil placeholderImage:(界面图像imageNamed: @ " gifTest.gif "]],其实,在SDWebImage这个库里有一个用户界面图像+ GIF的类别,里面为用户界面图像扩展了三个方法:
@ interface界面图像(GIF) + (IImage *) sd_animatedGIFNamed:(NSString *)名称; +(用户界面图像*)sd_animatedGIFWithData:(NSData *)数据; (用户界面图像*)sd_animatedImageByScalingAndCroppingToSize:(CGSize)大小; @end大家一看就知道,我们要获取处理后的Gif图片,其实只要调用前面两个中的其中一个方法就行了
注意:第一个只需要传Gif的名字,而不需要带扩展名(如Gif图片名字为001 @2x.gif,只需传001年即可)
我们就使用第二个方法试一试效果:
NSString *路径=[[NSBundle mainBundle] pathForResource: @减低:“礼物”@“gif”); NSData *数据=[NSData dataWithContentsOfFile路径):; 用户界面图像*图像=[界面图像sd_animatedGIFWithData:数据); gifImageView。形象=形象;然后通过断点,我们看下获取到的图像是个什么样的东东:
+(用户界面图像*)sd_animatedGIFWithData:数据(NSData *) { 如果数据(!){ 返回nil; } CGImageSourceRef源=CGImageSourceCreateWithData ((__bridge CFDataRef)数据,NULL); size_t数=CGImageSourceGetCount(源); 用户界面图像* animatedImage; 如果(计数& lt;=1) { animatedImage=[[界面图像alloc] initWithData:数据); } 其他{ NSMutableArray *图像=[NSMutableArray数组); NSTimeInterval时间=0.0度; (size_t我=0;我& lt;计数;我+ +){ CGImageRef图像=CGImageSourceCreateImageAtIndex(源、我空); 持续时间+=(自我sd_frameDurationAtIndex:我来源:源); (图片addObject:(界面图像imageWithCGImage:图像比例尺:[UIScreen mainScreen]。规模取向:UIImageOrientationUp]]; CGImageRelease(图片); } 如果持续时间(!){ 时间=(1.0 f f/10.0) *计数; } animatedImage=[界面图像animatedImageWithImages:图像持续时间:持续时间); } CFRelease(源); 返回animatedImage; }
iOS之加载Gif图片的方法