打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
iOS GIF 格式动画 图片显示

在 iOS 开发中,我们常使用 SDK 中的 UIImageView 显示图片,使用 UIImage 解码图片文件或数据,其支持 PNG, JEPG, BMP, GIF 等格式。其中 GIF 图片不支持动画。

如果中 iOS 中显示 GIF 动画图片,则需要自己实现。具体实现方式很简单,使用 SDK 中的 Image I/O framework 解码图片,读取 GIF 动画图片的帧数,显示时间。

然后使用 SDK 中的 quartzcore framework 中的 core animation 的 CAKeyFrameAnimation 类对 CALayer 执行动画。 

1. 解码图片,在  iOS Create an CGImageSource 文章已经介绍了如何使用 Image I/O framework 进行图片解码。

2. 读取 GIF 动画图片的每一帧图片及显示时间,并保存成数组:

  1. size_t imageCount = CGImageSourceGetCount(cImageSource);  
  2.     NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:imageCount];  
  3.     NSMutableArray *times = [[NSMutableArray alloc] initWithCapacity:imageCount];  
  4.     NSMutableArray *keyTimes = [[NSMutableArray alloc] initWithCapacity:imageCount];  
  5.       
  6.     float totalTime = 0;  
  7.     for (size_t i = 0; i < imageCount; i++) {  
  8.         CGImageRef cgimage= CGImageSourceCreateImageAtIndex(cImageSource, i, NULL);  
  9.         [images addObject:(__bridge id)cgimage];  
  10.         CGImageRelease(cgimage);  
  11.      
  12.         NSDictionary *properties = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(cImageSource, i, NULL);  
  13.         NSDictionary *gifProperties = [properties valueForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];  
  14.         NSString *gifDelayTime = [gifProperties valueForKey:(__bridge NSString* )kCGImagePropertyGIFDelayTime];  
  15.         [times addObject:gifDelayTime];  
  16.         totalTime += [gifDelayTime floatValue];  
  17.           
  18.         _size.width = [[properties valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];  
  19.         _size.height = [[properties valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];  
  20.     }  
  21.       
  22.     float currentTime = 0;  
  23.     for (size_t i = 0; i < times.count; i++) {  
  24.         float keyTime = currentTime / totalTime;  
  25.         [keyTimes addObject:[NSNumber numberWithFloat:keyTime]];  
  26.         currentTime += [[times objectAtIndex:i] floatValue];  
  27.     }  

3. 执行 CAKeyFrameAnimation 动画

  1. CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];  
  2.     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];  
  3.     [animation setValues:images];  
  4.     [animation setKeyTimes:keyTimes];  
  5.     animation.duration = totalTime;  
  6.     animation.repeatCount = HUGE_VALF;  
  7.     [self.layer addAnimation:animation forKey:@"gifAnimation"];  

完成!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
iOS开发中实现显示gif图片的方法
IOS 核心动画之CAKeyframeAnimation
OC 常用数据类型之间的转换
<ios> 谈谈iOS Animation </ios>
iOS开发 关键帧动画 CAKeyframeAnimation
iOS 常用小技巧大杂烩(上)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服