IOS 播放动态Gif图片

  图片分为静态和动态两种,图片的格式有很多种,在开发中比较常见的是.png和.jpg的静态图片,但有的时候在App中需要播放动态图片,比如.gif格式的小表情头像,在IOS中并没有提供直接显示动态图片的控件,下面就介绍几种显示动态图片的方式。

  <一>  UIImageView用来显示图片, 使用UIImageView中的动画数组来实现图片的动画效果

    //创建UIImageView,添加到界面
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
    [self.view addSubview:imageView];
    //创建一个数组,数组中按顺序添加要播放的图片(图片为静态的图片)
    NSMutableArray *imgArray = [NSMutableArray array];
    for (int i=1; i<7; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"clock%02d.png",i]];
        [imgArray addObject:image];
    }
    //把存有UIImage的数组赋给动画图片数组
    imageView.animationImages = imgArray;
    //设置执行一次完整动画的时长
    imageView.animationDuration = 6*0.15;
    //动画重复次数 (0为重复播放)
    imageView.animationRepeatCount = 0;
    //开始播放动画
    [imageView startAnimating];
    //停止播放动画  - (void)stopAnimating;
//判断是否正在执行动画  - (BOOL)isAnimating;

  <二>  用UIWebView来显示动态图片

    //得到图片的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"happy" ofType:@"gif"];
    //将图片转为NSData
    NSData *gifData = [NSData dataWithContentsOfFile:path];
    //创建一个webView,添加到界面
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 150, 200, 200)];
    [self.view addSubview:webView];
    //自动调整尺寸
    webView.scalesPageToFit = YES;
    //禁止滚动
webView.scrollView.scrollEnabled = NO;
    //设置透明效果
    webView.backgroundColor = [UIColor clearColor];
webView.opaque = 0;
    //加载数据
    [webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

  <三>  用第三方GifView显示本地图片

  GifView是封装好的一个类,可以直接导入程序中,然后创建对象,来显示动态图片;需要注意的是,GifView是MRC的,因此在ARC工程中使用它,需要修改标记 –fno-objc-arc

//方式一:显示本地Gif图片
    //将图片转为NSData数据
    NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bird" ofType:@"gif"]];
    //创建一个第三方的View显示图片
    GifView *dataView = [[GifView alloc] initWithFrame:CGRectMake(0, 300, 200, 100) data:localData];
    [self.view addSubview:dataView];

//方式二:显示本地Gif图片
    //得到图片的路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"gif"];
//创建一个第三方的View显示图片
    GifView *dataView2 = [[GifView alloc] initWithFrame:CGRectMake(200, 300, 150, 100) filePath:path];
    [self.view addSubview:dataView2];

//方式三:显示从网络获取的Gif图片
    // 网络图片
    NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic19.nipic.com/20120222/8072717_124734762000_2.gif"]];
    //创建一个第三方的View显示图片
    GifView *dataViewWeb = [[GifView alloc] initWithFrame:CGRectMake(20, 420, 280, 100) data:urlData];
    [self.view addSubview:dataViewWeb];

GifView.h

#import <UIKit/UIKit.h>
#import <ImageIO/ImageIO.h>

@interface GifView : UIView {
    CGImageSourceRef gif;
    NSDictionary *gifProperties;
    size_t index;
    size_t count;
    NSTimer *timer;
}

- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath;
- (id)initWithFrame:(CGRect)frame data:(NSData *)_data;

@end

GifView.m

#import "GifView.h"
#import <QuartzCore/QuartzCore.h>

@implementation GifView

- (id)initWithFrame:(CGRect)frame filePath:(NSString *)_filePath{

    self = [super initWithFrame:frame];
    if (self) {

        gifProperties = [[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount]
                                                     forKey:(NSString *)kCGImagePropertyGIFDictionary] retain];
        gif = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:_filePath], (CFDictionaryRef)gifProperties);
        count =CGImageSourceGetCount(gif);
        timer = [NSTimer scheduledTimerWithTimeInterval:0.12 target:self selector:@selector(play) userInfo:nil repeats:YES];
        [timer fire];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame data:(NSData *)_data{

    self = [super initWithFrame:frame];
    if (self) {

        gifProperties = [[NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount]
                                                     forKey:(NSString *)kCGImagePropertyGIFDictionary] retain];
       gif = CGImageSourceCreateWithData((CFDataRef)_data, (CFDictionaryRef)gifProperties);
        count =CGImageSourceGetCount(gif);
        timer = [NSTimer scheduledTimerWithTimeInterval:0.12 target:self selector:@selector(play) userInfo:nil repeats:YES];
        [timer fire];
    }
    return self;
}

-(void)play
{
    index ++;
    index = index%count;
    CGImageRef ref = CGImageSourceCreateImageAtIndex(gif, index, (CFDictionaryRef)gifProperties);
    self.layer.contents = (id)ref;
    CFRelease(ref);
}
-(void)removeFromSuperview
{
    NSLog(@"removeFromSuperview");
    [timer invalidate];
    timer = nil;
    [super removeFromSuperview];
}
- (void)dealloc {
    NSLog(@"dealloc");
    CFRelease(gif);
    [gifProperties release];
    [super dealloc];
}
@end

<四> 总结

  1、通过UIImageView显示动画效果,实际上是把动态的图拆成了一组静态的图,放到数组中,播放的时候依次从数组中取出。如果播放的图片比较少占得内存比较小或者比较常用(比如工具条上一直显示的动态小图标),可以选择用imageNamed:方式获取图片,但是通过这种方式加到内存中,使用结束,不会自己释放,多次播放动画会造成内存溢出问题。因此,对于大图或经常更换的图,在取图片的时候可以选择imageWithContentsOfFile:方式获取图片,优化内存。

  2、使用UIWebView显示图片需要注意显示图片的尺寸与UIWebView尺寸的设置,如果只是为了显示动态图片,可以禁止UIWebView滚动。在显示动态图片的时候,即使是动图的背景处为透明,默认显示出来是白色背景,这个时候需要手动设置UIWebView的透明才能达到显示动图背景透明的效果。

  3、第三方的GifView使用比较简单,把类导入即可。但是GifView是MRC的,因此在ARC环境下,需要对类进行标识。

  4、UIImageView与第三方的GifView都是通过定时器来控制图片模拟的动画,播放的时候是设置每一帧的时长,因此在使用的时候,要尽量与动图原本的时长靠近,不然动画效果会有些奇怪。而通过UIWebView加载Gif动图的时候会保持原有的帧速,不需要再次设置。

  想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。

  疑问咨询或技术交流,请加入官方QQ群: (452379712)

作者:杰瑞教育

出处:http://blog.csdn.net/jerehedu/

本文版权归烟台杰瑞教育科技有限公司和CSDN共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

时间: 2024-08-26 05:48:07

IOS 播放动态Gif图片的相关文章

iOS播放动态GIF图片

<转> 图片分为静态和动态两种,图片的格式有很多种,在开发中比较常见的是.png和.jpg的静态图片,但有的时候在App中需要播放动态图片,比如.gif格式的小表情头像,在IOS中并没有提供直接显示动态图片的控件,下面就介绍几种显示动态图片的方式. <一>  UIImageView用来显示图片, 使用UIImageView中的动画数组来实现图片的动画效果 //创建UIImageView,添加到界面 UIImageView *imageView = [[UIImageView all

iOS本地动态验证码生成-b

用于ios本地动态生成验证码,效果如下: demo.gif 导入CoreGraphics.framework用于绘制图形 封装UIView,便捷使用,代码如下: AuthcodeView.h #import <UIKit/UIKit.h> @interface AuthcodeView : UIView @property (strong, nonatomic) NSArray *dataArray;//字符素材数组 @property (strong, nonatomic) NSMutabl

社交应用动态九宫格图片的规则

这里主要以微信和QQ空间为作为研究对象,得到的结论如下. QQ空间里的动态 iOS设备,以iPhone6为分界 iPhone6及以上分辨率的设备: 当宽且高同时 > 512px时,判断 宽/高的比例值:大于 2时,以高度为基准,缩小到512px,宽度等比缩.小于等于 2时,以宽度为基准,缩小到512px,高度等比缩 当宽.高其中一边小于512px,直接下原图: iPhone6以下的设备(5s.SE.4s),判断条件同上,只是将512px改为200px Android规则同上,只是以1280分辨率

iOS播放音乐

http://www.jianshu.com/p/ce279bc773dd iOS播放音乐.后台播放.控制台控制相关的一些TIPS,基于StreamingKit 字数963 阅读595 评论0 喜欢9 首先给大家放一个StreamingKit的链接 简单的播放使用例子,可以看开源作者的演示demo. 由于整个播放器涉及到UI啊数据啊比较多,所以就不全抠下来当demo了,就在这里列一点TIPS,希望能帮助到大家. 歌曲播放形式我是这么写的: .h里: /** 歌曲播放形式 */ typedef e

ios播放视频demo

今天要用到ios原生态播放一段网络视频,在此整理共享出来 白白手游专栏http://blog.csdn.net/u010229677 首先需要给工程添加框架MediaPlayer.Framework #import "ViewController.h" #import <MediaPlayer/MediaPlayer.h> @interface ViewController () { MPMoviePlayerViewController *playerViewContro

动态设置图片的宽度和高度

动态设置图片控件的宽度和高度: imageView.getLayoutParams().width=600;imageView.getLayoutParams().height=400; 设置图片(src): imageView.setImageResource(resId); android获得屏幕高度和宽度: 1.WindowManager wm = (WindowManager) getContext()                     .getSystemService(Cont

iOS.TextKit.02.文字图片混合排版

1.案例如图 2.代码 TextKit02ViewController.h #import <UIKit/UIKit.h> @interface TextKit02ViewController : UIViewController @property (nonatomic,strong) IBOutlet UITextView *textView; @property (nonatomic,weak) IBOutlet UIImageView *imageView; // 文本可以排版的区域

js 动态修改属性值 动态修改图片,字等

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv = "content-type" content="text/html;charset=utf-8"/> &

iOS一行代码压缩图片大小

现在基本所有应用都与图片相关联,这就必然涉及到上传下载图片,而用户的流量又迟迟没有被解放,因此图片就不能太大,我们知道iPhone一张照片动辄几M,如果都传原图那流量就会爆炸,粗暴地缩小又会影响图片的分辨率.那有没有办法在保持一定分辨率的情况下压缩图片呢?有的,而且非常简单,一行代码搞定,是苹果自带的压缩函数: UIImageJPEGRepresentation UIImagePNGRepresentation 这两个函数都是iOS自带的图片压缩工具.一个是压成JPEG格式,一个是压成PNG格式