iOS开发之展示gif图像

元景天
2023-12-01

这个也是这段时间解决的问题,展示gif图像,在这里给大家也分享一下

1.使用SDWebImage

SDWebImage比较占内存,但是问题不大

导入头文件

#import "UIImage+GIF.h"

设置gif图

self.imageView.image = [UIImage sd_animatedGIFNamed:@"test"];

也可以通过NSData导入

+ (UIImage *)sd_animatedGIFWithData:(NSData *)data

原理:

1.将gif图的每一帧导出为一个UIImage,并且算出每一帧的播放时间,将导出的image放入images数组中
2.使用+ animatedImageWithImages: duration: 方法创建image,参数为第一步的images数组和播放总时长
3.设置UIImageView的image时用sd_animatedGIFNamed:方法即可展示gif

2.使用FLAnimatedImage

导入头文件

#import "FLAnimatedImage.h"

设置gif图

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"gif"];

NSData *data = [NSData dataWithContentsOfFile:path];

FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:data];

self.imageView.animatedImage = image;

3.使用WebView进行展示

特点:加载速度略长,但是性能更优,播放的gif动态图更加流畅。

//动态展示GIF图片-WebView
-( void )showGifImageWithWebView{
  //读取gif图片数据
  NSData *gifData = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@ "earthGif" ofType:@ "gif" ]];
  //UIWebView生成
  UIWebView *imageWebView = [[UIWebView alloc] initWithFrame:CGRectMake(112, 302, 132, 102)];
  //用户不可交互
  imageWebView.userInteractionEnabled = NO;
  //加载gif数据
  [imageWebView loadData:gifData MIMEType:@ "image/gif" textEncodingName:nil baseURL:nil];
  //视图添加此gif控件
  [self.view addSubview:imageWebView];
4.创建UIImageView的一个类别
加载的方式更加快速,性能不如UIWebView,优点:易于扩展,需要导入#import <ImageIO/ImageIO.h>
.h文件
/** 解析gif文件数据的方法 block中会将解析的数据传递出来 */
-(void)getGifImageWithUrk:(NSURL *)url returnData:(void(^)(NSArray<UIImage *> * imageArray,NSArray<NSNumber *>*timeArray,CGFloat totalTime, NSArray<NSNumber *>* widths, NSArray<NSNumber *>* heights))dataBlock;

/** 为UIImageView添加一个设置gif图内容的方法: */
-(void)yh_setImage:(NSURL *)imageUrl;

.m文件

//解析gif文件数据的方法 block中会将解析的数据传递出来
-(void)getGifImageWithUrk:(NSURL *)url returnData:(void(^)(NSArray<UIImage *> * imageArray, NSArray<NSNumber *>*timeArray,CGFloat totalTime, NSArray<NSNumber *>* widths,NSArray<NSNumber *>* heights))dataBlock{
    //通过文件的url来将gif文件读取为图片数据引用
    CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    //获取gif文件中图片的个数
    size_t count = CGImageSourceGetCount(source);
    //定义一个变量记录gif播放一轮的时间
    float allTime=0;
    //存放所有图片
    NSMutableArray * imageArray = [[NSMutableArray alloc]init];
    //存放每一帧播放的时间
    NSMutableArray * timeArray = [[NSMutableArray alloc]init];
    //存放每张图片的宽度 (一般在一个gif文件中,所有图片尺寸都会一样)
    NSMutableArray * widthArray = [[NSMutableArray alloc]init];
    //存放每张图片的高度
    NSMutableArray * heightArray = [[NSMutableArray alloc]init];
    //遍历
    for (size_t i=0; i<count; i++) {
        CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
        [imageArray addObject:(__bridge UIImage *)(image)];
        CGImageRelease(image);
        //获取图片信息
        NSDictionary * info = (__bridge NSDictionary*)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
        CGFloat width = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelWidth] floatValue];
        CGFloat height = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelHeight] floatValue];
        [widthArray addObject:[NSNumber numberWithFloat:width]];
        [heightArray addObject:[NSNumber numberWithFloat:height]];
        NSDictionary * timeDic = [info objectForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
        CGFloat time = [[timeDic objectForKey:(__bridge NSString *)kCGImagePropertyGIFDelayTime]floatValue];
        allTime+=time;
        [timeArray addObject:[NSNumber numberWithFloat:time]];
    }
    dataBlock(imageArray,timeArray,allTime,widthArray,heightArray);
}

//为UIImageView添加一个设置gif图内容的方法:
-(void)yh_setImage:(NSURL *)imageUrl{
    __weak id __self = self;
    [self getGifImageWithUrk:imageUrl returnData:^(NSArray<UIImage *> *imageArray, NSArray<NSNumber *> *timeArray, CGFloat totalTime, NSArray<NSNumber *> *widths, NSArray<NSNumber *> *heights) {
        //添加帧动画
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
        NSMutableArray * times = [[NSMutableArray alloc]init];
        float currentTime = 0;
        //设置每一帧的时间占比
        for (int i=0; i<imageArray.count; i++) {
            [times addObject:[NSNumber numberWithFloat:currentTime/totalTime]];
            currentTime+=[timeArray[i] floatValue];
        }
        [animation setKeyTimes:times];
        [animation setValues:imageArray];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
        //设置循环
        animation.repeatCount= MAXFLOAT;
        //设置播放总时长
        animation.duration = totalTime;
        //Layer层添加
        [[(UIImageView *)__self layer]addAnimation:animation forKey:@"gifAnimation"];
    }];
}

方法使用:

UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(f_Device_w*i, 0, f_Device_w, f_Device_h)];
        NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"http://ycbook.11space.cn%@",imgArray[i]]];
        [imageView yh_setImage:url];
        [self.view addSubview:imageView];

展示gif动图的UIImageView类别源码:https://github.com/hbblzjy/UIImageViewTool

有问题请留言。。。


 类似资料: