iOS 加载Gif图片

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文件内,如下图所示

- (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
导入UIImage+GIF头文件
NSString *path = [[NSBundle mainBundle] pathForResource:@"gifTest" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    UIImage *image = [UIImage sd_animatedGIFWithData:data];
    gifImageView.image = image;
君凯商联网-iOS-字唐名僧









  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值