iOS之加载Gif图片

作者: 镜花水月_I | 来源:发表于2016-03-14 18:50 被阅读42218次

Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁。但是iOS竟然没有现成的支持加载和播放Gif的类。

简单地汇总了一下,大概有以下几种方法:

一、加载本地Gif文件

1、使用UIWebView

    // 读取gif图片数据 
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,200,200)];
    [self.view addSubview:webView];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"001" ofType:@"gif"];
    /*
         NSData *data = [NSData dataWithContentsOfFile:path];
         使用loadData:MIMEType:textEncodingName: 则有警告
         [webView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
     */
    NSURL *url = [NSURL URLWithString:path];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];

但是使用UIWebView的弊端在于,不能设置Gif动画的播放时间。

2、将Gif拆分成多张图片,使用UIImageView播放

最好把所需要的Gif图片打包到Bundle文件内,如下图所示

Loading.png
- (NSArray *)animationImages
{
    NSFileManager *fielM = [NSFileManager defaultManager];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Loading" ofType:@"bundle"];
    NSArray *arrays = [fielM contentsOfDirectoryAtPath:path error:nil];
    
    NSMutableArray *imagesArr = [NSMutableArray array];
    for (NSString *name in arrays) {
        UIImage *image = [UIImage imageNamed:[(@"Loading.bundle") stringByAppendingPathComponent:name]];
        if (image) {
            [imagesArr addObject:image];
        }
    }
    return imagesArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:frame];
    gifImageView.animationImages = [self animationImages]; //获取Gif图片列表
    gifImageView.animationDuration = 5;     //执行一次完整动画所需的时长
    gifImageView.animationRepeatCount = 0;  //动画重复次数
    [gifImageView startAnimating];
    [self.view addSubview:gifImageView];
}

3、使用SDWebImage

但是很遗憾,SDWebImagesd_setImageWithURL:placeholderImage:这个方法是不能播放本地Gif的,它只能显示Gif的第一张图片而已。So,此方法行不通

    UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:frame];
    [gifImageView sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"gifTest.gif"]];

其实,在SDWebImage这个库里有一个UIImage+GIF的类别,里面为UIImage扩展了三个方法:

@interface UIImage (GIF)
+ (IImage *)sd_animatedGIFNamed:(NSString *)name;
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data;
- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
@end

大家一看就知道,我们要获取处理后的Gif图片,其实只要调用前面两个中的其中一个方法就行了

注意:第一个只需要传Gif的名字,而不需要带扩展名(如Gif图片名字为001@2x.gif,只需传001即可)



我们就使用第二个方法试一试效果:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage sd_animatedGIFWithData:data];
    gifImageView.image = image;

然后通过断点,我们看下获取到的image是个什么样的东东:

img.png

我们发现:

image的isa指针指向了_UIAnimatedImage ,说明它是一个叫作_UIAnimatedImage 的类(当然,这个_UIAnimatedImage 苹果是不会直接让我们使用的)

_images 表示:这个Gif包含了多少张图片

_duration表示:执行一次完整动画所需的时长

其实,动画执续时间_duration也可以更改!
我们来看下此方法的内部实现:


+ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
    if (!data) {
        return nil;
    }

    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);

    size_t count = CGImageSourceGetCount(source);

    UIImage *animatedImage;

    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
    }
    else {
        NSMutableArray *images = [NSMutableArray array];

        NSTimeInterval duration = 0.0f;

        for (size_t i = 0; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);

            duration += [self sd_frameDurationAtIndex:i source:source];

            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];

            CGImageRelease(image);
        }

        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }

        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
    }

    CFRelease(source);

    return animatedImage;
}

很明显,duration是可以随意更改的,只不过此方法设置了一个默认值
(duration = (1.0f / 10.0f) * count)

归根到底,创建新的动态的Image其实是调用了系统提供的一个UIImage的类方法而已:

 UIImage *animatedImage = [UIImage animatedImageWithImages:images duration:duration];

二、加载网络Gif文件

加载网络的Gif文件就简单多了。最简单的方法,我们只需要使用SDWebImagesd_setImageWithURL:这个方法传入Gif文件是url地址即可。
纠其原因:稍微仔细看了SDWebImage内部实现就可以清楚,大概是以下几个步骤:

1、SDWebImage根据url将Gif文件下载下来,格式为一个NSData
2、如果判断是Gif格式,则会调用** sd_animatedGIFWithData:** 将Data转换成我们需要的Gif格式
3、通过上面的方法二即可显示出Gif图片

UIImage *image = [UIImage sd_animatedGIFWithData:data];
gifImageView.image = image;

............................................................

总结

一、加载本地Gif文件

1、使用UIWebView不可以设置duration,其他两种方法都可设置。而且方法1的容器为UIWebView ,其余两种的容器都是大家熟悉的UIImageView
2、方法2和方法3需要对应看应用场景

如:下拉、上拉加载控件需要一个根据拉动距离设置特定的Image,则需要使用方法2

直接显示Gif图片,则使用方法3会更方便

二、加载网络Gif文件

直接使用SDWebImagesd_setImageWithURL:这个方法传入Gif文件是url地址即可

............................................................

PS:简单小Demo

相关文章

  • Swift (四) gif图片播放

    @[TOC](IOS gif图片播放 swift) 1. GIF在iOS平台上的几种加载方式 使用Dispatch...

  • 加载Gif图片

    转载:iOS之加载Gif图片作者:镜花水月_I 1、使用UIWebView 但是使用UIWebView的弊端在于,...

  • iOS SDWebImage 加载GIF图片没效果

    //加载本地GIF图片 //加载网络GIF图片 (SDWebImage 4.0 之前) //加载网络GIF图片(S...

  • iOS之加载Gif图片

    Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁。但是iOS竟然没有现成的支持加载和播...

  • gif图片

    关键是不能直接使用UIImage,而是转成NSData来处理 一,iOS之加载Gif图片 其实,在SDWebIma...

  • Android Glide 使用

    加载 GIF 图片到 ImageView 中 通常 Android 的 ImageView 不能加载 Gif 图片...

  • Xcode开发播放gif图片

    在开发iOS程序的过程中,可能会遇到要加载gif图片,下面介绍gif图片的加载方式:先介绍一个第三方:gifVie...

  • iOS Gif图片加载

    Gif图片如越来越受欢迎,移动端对它的支持也是有些知识点的,主要是加载图片性能优化 Gif图片的生成 Gif图片是...

  • iOS加载gif图片

    1、通过拆分gif,加载一个图片数组(推荐一个Mac APP自动拆分gif:Gif Preview) 2、UIWe...

  • iOS加载Gif图片

    Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁。但是iOS竟然没有现成的支持加载和播...

网友评论

  • 晓晓521:使用第二种方法怎么让gif图 播放一次呢?
    我本善良:我也是同问,启动展示gif怎么让展示一次,停在最后一帧图片呢
  • 曾经像素有点低:https://piccdn.gracg.com/uploadfile/photo/2014/1/13889853728975.gif

    这张GIF图为什么用webView是动图。但是用sd_animatedGIFWithData是不动的
  • Lazyloading:请问怎么让gif只显示一次就停止呢 现在一直在循环显示
    晓晓521:同求啊 我也遇到了 使用第二种方法怎么让gif图 播放一次呢?
  • 连命都给你了:我测过两这几种方法,一个是sd的setimage方法直接播放URL地址就行了,最方便简单效果好,还有一个方法是使用flanimationimage,使用sdwebimagemanager初始化后,调用loadimage方法在回调内拿到gif的data,在这里进入主线程然后给fl类的imageview调用setanimateimage也行,webview展示效果不好
  • 清风明月伴我行:如何停止动画 ,只能移除imgview么
  • afe947a1a0fd:sdwebimage 加载gif有iOS系统版本限制吗
  • d976e6bc9ea9:蛮赞的,整理的挺全的。
  • 乂滥好人:可以的,谢谢分享
  • _君莫笑_:NSString *path = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage sd_animatedGIFWithData:data];
    gifImageView.image = image;
    这个方法不好使,你自己没有试吗?
    镜花水月_I:这方法没问题,我已附上Demo地址
  • 150c8fb584ef:我加载本地Gif文件,用了SDWebImage,
    NSString *path = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage sd_animatedGIFWithData:data];
    gifImageView.image = image;

    把代码设置了之后,gif就显示动图了,打断点显示的不是_UIAnimatedImage,也就没设置_duration,但是gif图闪动的速度很快
    __block:@Jarvan07 额,好的,谢谢啦
    150c8fb584ef:@__block 我就换了一个慢点的gif图,不知道速度快是怎么回事
    __block:你好, 我现在也遇到了这个问题, 请问你解决了吗...
  • 煮石散人:共享一个小 demo ,在 GitHub 上。https://github.com/zssr/GifBackgroundView
  • 阿斯兰iOS:使用sd播放gif,不管本地还是网络的,都要使用FLAnimatedImageView。
    #import "FLAnimatedImageView+WebCache.h"
    FLAnimatedImageView *iv = [FLAnimatedImageView new];
    [iv sd_setImageWithURL:url];
    sd的sd_animatedGIFWithData方法返回的image只包含第一帧。
  • coder小鹏:mark,整理的非常全
  • XTShow:友情提示:relaxed:
    SDWebImage, 3.8.2里,<SDWebImage/UIImage+GIF.h>类中的sd_animatedGIFWithData方法,已经支持使用本地gif文件了~~~
    阿斯兰iOS:@没有人知道我是谁丨让我吐槽个够 sd版本不一样,我的是4.0的。
    在UIImage+GIF.h里面
    ```
    #import "SDWebImageCompat.h"

    @interface UIImage (GIF)

    /**
    * Compatibility method - creates an animated UIImage from an NSData, it will only contain the 1st frame image
    */
    + (UIImage *)sd_animatedGIFWithData:(NSData *)data;

    /**
    * Checks if an UIImage instance is a GIF. Will use the `images` array
    */
    - (BOOL)isGIF;

    @EnD
    ```
    不知道评论里能不能显示代码。。。
    XTShow:@阿斯兰iOS 您复制这句话我确实没有在哪看到,但是我说的方式是我自己实现了的;要不然也不可能来这回复啊。。。
    阿斯兰iOS:Compatibility method - creates an animated UIImage from an NSData, it will only contain the 1st frame image
  • 花式写法:现在sdWebImage上的gif只有sd_animatedGIFWithData这一个方法了 而且我试了试只显示第一张,不知道为什么.
    serenade07:@花式写法 我知道怎么回事了,刚刚仔细看了github上面的说明,4.0版本就是这样的,要导入FLAnimatedImageView, instead of UIImageView, if you are still trying to load a GIF into a UIImageView, it will only show the 1st frame as a static image.
    serenade07:@花式写法 我也是的,而且我一开始使用的时候老是报错,说FLAnimatedImage不存在,我就把这个文件夹删掉,就好了。看上面的人说跟这个有关
  • X了个code:为什么我通过第三种 或者 sdwebimage 的url 加载本地GIF 都为静态 好烦
    凉风起君子意如何:现在确实更新了,这样改下就可以
    FLAnimatedImageView *imgView = [FLAnimatedImageView new];
    [view addSubview:imgView];
    NSString* filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]]pathForResource:@"loading" ofType:@"gif"];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    imgView.backgroundColor = [UIColor clearColor];
    imgView.animatedImage = [FLAnimatedImage animatedImageWithGIFData:imageData];
    X了个code:@镜花水月_I 看了下文档,现在好像变了 ,是在FLAnimatedImage上弄gif动画
    镜花水月_I:@X了个code 哥们,你可能要再仔细看看我写的。
  • 张云龙:SDWebImage貌似可以显示git,我的项目里有一张git直接显示了
    张云龙:@镜花水月_I 是的
    镜花水月_I:@张云龙 SDWebImage 可以通过url 直接加载gif,因为它内部已经对GIF做了处理了
    无夜之星辰:@张云龙 有没有什么办法可以加载网络GIF图片?
  • Jong_HR:楼主你好!我想问一下,怎么加载一张从服务器获取的GIF图片,只让他显示第一张图片,不让它动,SDWebImage里面有没有这个方法,普通的网络请求也可以,但是太慢了
    Jong_HR:@镜花水月_I 这样做的话,在下载完成之前,图片的位置还是空白的啊
    一个很帅的蓝孩子:@一點點在乎 sd_animatedGIFNamed这个就可以设置的 只显示第一张不会动 sd_animatedGIFWithData这个是可以显示GIF动图 我也刚做了
    镜花水月_I:@一點點在乎 只能先下载下来,然后使用 [imageView setImage:[UIImage imageNamed:@"gifTest.gif"]];
  • 042a0e1be73f:[webView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    这里发出警告
    Null passed to a callee that requlres a non-null argument
    寡妇村村長:不能传nil
    CoderChou:@iiOS 对啊,这个我也没有解决警告。
  • 罗同学_:加载的gift图片不会动怎么办,没有gift图的效果
    一个很帅的蓝孩子:@四韦夕人 那你应该是用的这个 sd_animatedGIFNamed 用sd_animatedGIFWithData就可以显示GIF动图
    罗同学_:@镜花水月_I 我是用的第三种啊
    镜花水月_I:@单手两万行无bug 如果你直接用UIImageView 加载这个gif图片的话,其实是取的gif第一张图片,当然不会动咯。你可以试一试我上面的第三种方法
  • 101513527ed6:看天书一样

本文标题:iOS之加载Gif图片

本文链接:https://www.haomeiwen.com/subject/xfbflttx.html