iOS GIF 格式动画 图片显示
2016-06-23 13:25
441 查看
iOS GIF 格式动画 图片显示
标签: ios动画uiimageview图片2014-02-09 23:04 7984人阅读 评论(2) 收藏 举报
分类:
iOS(6)
版权声明:本文为博主原创文章,未经博主允许不得转载。
在 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 动画图片的每一帧图片及显示时间,并保存成数组:
[objc] view
plain copy
size_t imageCount = CGImageSourceGetCount(cImageSource);
NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:imageCount];
NSMutableArray *times = [[NSMutableArray alloc] initWithCapacity:imageCount];
NSMutableArray *keyTimes = [[NSMutableArray alloc] initWithCapacity:imageCount];
float totalTime = 0;
for (size_t i = 0; i < imageCount; i++) {
CGImageRef cgimage= CGImageSourceCreateImageAtIndex(cImageSource, i, NULL);
[images addObject:(__bridge id)cgimage];
CGImageRelease(cgimage);
NSDictionary *properties = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(cImageSource, i, NULL);
NSDictionary *gifProperties = [properties valueForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
NSString *gifDelayTime = [gifProperties valueForKey:(__bridge NSString* )kCGImagePropertyGIFDelayTime];
[times addObject:gifDelayTime];
totalTime += [gifDelayTime floatValue];
_size.width = [[properties valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
_size.height = [[properties valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
}
float currentTime = 0;
for (size_t i = 0; i < times.count; i++) {
float keyTime = currentTime / totalTime;
[keyTimes addObject:[NSNumber numberWithFloat:keyTime]];
currentTime += [[times objectAtIndex:i] floatValue];
}
3. 执行 CAKeyFrameAnimation 动画
[objc] view
plain copy
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[animation setValues:images];
[animation setKeyTimes:keyTimes];
animation.duration = totalTime;
animation.repeatCount = HUGE_VALF;
[self.layer addAnimation:animation forKey:@"gifAnimation"];
完成!
相关文章推荐
- 本地存储 之 NSUserDefaults 及NSUserDefaults对存储对象的封装
- iOS8以iOS8以下的系统present一个半透明的ViewController的方法
- xcode ios调试 NSLog没有输出 控制台没有输出解决
- iOS之手机信号的查看与判断
- NSMakeRange,substringWithRange,substringToIndex,substringFromIndex区别和联系
- 简便方法IOS中自适应文字高度
- IOS-10行代码搞定九宫格
- IOS开发中使用自定义键盘
- 开发者所需要知道的 iOS 10 SDK 新特性
- 文章标题
- iOS9适配 之 关于info.plist 第三方登录 添加URL Schemes白名单
- iOS--优秀博客记录
- iOS开发笔记--如何实现程序长时间未操作退出
- 解决iOS 控制器继承后,控制器侧滑失效的问题
- iOS 常写在pch中的设备区分
- CGImageCreateWithImageInRect图片裁剪问题
- iOS 手势滑动返回功能
- ios::sync_with_stdio(false);(读入优化)
- iOS TableView实现QQ好友列表
- iOS开发:字典(NSDictionary)和数组( NSArray)转换成字符串