iOS显示gif图片的几种方法

韩智敏
2023-12-01

方法一、传统方式

//1.加载Gif图片,转换成Data类型
    NSString *path = [NSBundle.mainBundle pathForResource:@"demo" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    //2.将data数据转换成CGImageSource对象
    CGImageSourceRef imageSource = CGImageSourceCreateWithData(CFBridgingRetain(data), nil);
    size_t imageCount = CGImageSourceGetCount(imageSource);
    
    //3.遍历所有图片
    NSMutableArray *images = [NSMutableArray array];
    NSTimeInterval totalDuration = 0;
    for (int i = 0; i<imageCount; i++) {
        //取出每一张图片
        CGImageRef cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil);
        UIImage *image = [UIImage imageWithCGImage:cgImage];
        [images addObject:image];
        
        //持续时间
        NSDictionary *properties = (__bridge_transfer  NSDictionary*)CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil);
        NSDictionary *gifDict = [properties objectForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
        NSNumber *frameDuration =
        [gifDict objectForKey:(__bridge NSString *)kCGImagePropertyGIFDelayTime];
        totalDuration += frameDuration.doubleValue;
    }
    
    //4.设置imageView属性
    self.imageView.animationImages = images;
    self.imageView.animationDuration = totalDuration;
    self.imageView.animationRepeatCount = 0;
    
    //5.开始播放
    [self.imageView startAnimating];

完整代码:https://github.com/dolacmeng/gifDemo

方法二、第三方框架FLAnimatedImage

利用FLAnimatedImage可以快速添加一个gif图片到视图,如添加名称为test_gif.gif的图片:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test_gif" ofType:@"gif"];
NSURL *url = [NSURL fileURLWithPath:filePath];
FLAnimatedImage *gest = [FLAnimatedImage animatedImageWithGIFData: [NSData dataWithContentsOfURL:url]];
FLAnimatedImageView *gestImageView = [[FLAnimatedImageView alloc] init];
gestImageView.animatedImage = gest;
gestImageView.frame = CGRectMake(461, 311, 119.5, 113);
[view addSubview:gestImageView];

方法三、利用UIWebView

如利用UIWebView加载名称为test_gif.png的图片:

UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _imageW, _imageH)];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"test_gif" ofType:@"gif"];
NSData *imgData = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:imgData];
bgImageView.image = image;
 [self.bgScrollView addSubview:bgImageView];

优化多个Gif同时播放卡顿的问题

在我的实际开发中,有个需求是在一个页面中显示多个Gif动画,利用上面的方法,都会有卡顿不流畅的问题,经过与设计狮的沟通,提出了将gif文件转化为apng格式,再用方法三的方式用UIWebView加载就不卡顿了。

 类似资料: