UIImageView+Extension.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // UIImageView+Extension.m
  3. // Timi
  4. //
  5. // Created by 翟玉磊 on 2021/5/18.
  6. //
  7. #import "UIImageView+Extension.h"
  8. @implementation UIImageView (Extension)
  9. - (void)loadGIFImageNamed:(NSString *)name {
  10. /// 找到GIF图片文件路径
  11. NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:name withExtension:@"gif"];
  12. /// 将GIF图片转换成对应的图片资源
  13. CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((__bridge CFURLRef)fileUrl, NULL);
  14. /// 从图片资源中获取图片帧数,即由多少图片元素组成(注:GIF图片本质是有多张图片合成流动图片)
  15. size_t imageCount = CGImageSourceGetCount(imageSourceRef);
  16. /// 定义数组拆分图片源
  17. NSMutableArray *images = [NSMutableArray arrayWithCapacity:imageCount];
  18. /// 定义动画持续时长
  19. float animationDuration = 0.f;
  20. /// 循环获取图片元素
  21. for(size_t i = 0; i < imageCount; i++) {
  22. /// 从图片资源中取出图片元素,即每一帧的图片
  23. CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSourceRef, i ,NULL);
  24. ///图片转换
  25. UIImage *image = [UIImage imageWithCGImage:imageRef];
  26. ///存储图片
  27. [images addObject:image];
  28. ///获取元素图片的信息
  29. NSDictionary *imageElementInfo = (__bridge NSDictionary*)CGImageSourceCopyProperties(imageSourceRef,NULL);
  30. ///获取元素动画信息
  31. NSDictionary *imageElementGIFInfo = [imageElementInfo objectForKey:(__bridge NSString*)kCGImagePropertyGIFDictionary];
  32. /// 初始化每帧之间间隔的属性。
  33. CGFloat duration = 0.1f;
  34. NSNumber *unclampedDelayTime = [imageElementGIFInfo objectForKey:(__bridge NSString*)kCGImagePropertyGIFUnclampedDelayTime];
  35. if(unclampedDelayTime) {
  36. duration = unclampedDelayTime.floatValue;
  37. } else {
  38. NSNumber *delayTime = [imageElementGIFInfo objectForKey:(__bridge NSString*)kCGImagePropertyGIFDelayTime];
  39. if (delayTime) {
  40. duration = delayTime.floatValue;
  41. }
  42. }
  43. /// 获取延迟时间可能为0.f
  44. if(duration <= 0.011f) duration = 0.100f;
  45. animationDuration += duration;
  46. ///释放内存
  47. CGImageRelease(imageRef);
  48. }
  49. /// 图片控件载入动画图片数组
  50. self.animationImages = images;
  51. /// 设置动画持续时长
  52. self.animationDuration = animationDuration;
  53. /// 设置动画重复次数
  54. self.animationRepeatCount = 0;
  55. ///开启动画
  56. [self startAnimating];
  57. }
  58. @end