123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- //
- // UIImageView+Extension.m
- // Timi
- //
- // Created by 翟玉磊 on 2021/5/18.
- //
- #import "UIImageView+Extension.h"
- @implementation UIImageView (Extension)
- - (void)loadGIFImageNamed:(NSString *)name {
-
- /// 找到GIF图片文件路径
- NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:name withExtension:@"gif"];
- /// 将GIF图片转换成对应的图片资源
- CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((__bridge CFURLRef)fileUrl, NULL);
-
- /// 从图片资源中获取图片帧数,即由多少图片元素组成(注:GIF图片本质是有多张图片合成流动图片)
- size_t imageCount = CGImageSourceGetCount(imageSourceRef);
- /// 定义数组拆分图片源
- NSMutableArray *images = [NSMutableArray arrayWithCapacity:imageCount];
- /// 定义动画持续时长
- float animationDuration = 0.f;
-
- /// 循环获取图片元素
- for(size_t i = 0; i < imageCount; i++) {
- /// 从图片资源中取出图片元素,即每一帧的图片
- CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef, i ,NULL);
- ///图片转换
- UIImage *image = [UIImage imageWithCGImage:imageRef];
- ///存储图片
- [images addObject:image];
- ///获取元素图片的信息
- NSDictionary *imageElementInfo = (__bridge NSDictionary*)CGImageSourceCopyProperties(imageSourceRef,NULL);
- ///获取元素动画信息
- NSDictionary *imageElementGIFInfo = [imageElementInfo objectForKey:(__bridge NSString*)kCGImagePropertyGIFDictionary];
- /// 初始化每帧之间间隔的属性。
- CGFloat duration = 0.1f;
- NSNumber *unclampedDelayTime = [imageElementGIFInfo objectForKey:(__bridge NSString*)kCGImagePropertyGIFUnclampedDelayTime];
- if(unclampedDelayTime) {
- duration = unclampedDelayTime.floatValue;
- } else {
- NSNumber *delayTime = [imageElementGIFInfo objectForKey:(__bridge NSString*)kCGImagePropertyGIFDelayTime];
- if (delayTime) {
- duration = delayTime.floatValue;
- }
-
- }
-
- /// 获取延迟时间可能为0.f
- if(duration <= 0.011f) duration = 0.100f;
- animationDuration += duration;
- ///释放内存
- CGImageRelease(imageRef);
- }
- /// 图片控件载入动画图片数组
- self.animationImages = images;
-
- /// 设置动画持续时长
- self.animationDuration = animationDuration;
- /// 设置动画重复次数
- self.animationRepeatCount = 0;
- ///开启动画
- [self startAnimating];
- }
- @end
|