ios如何加载gif图片
直接使用SDWebImage第三方库就可以了
这里主要使用了UIImage的类方法
+ (nullable UIImage *)animatedImageWithImages:(NSArray<UIImage *> *)images duration:(NSTimeInterval)duration NS_AVAILABLE_IOS(5_0);
需要两个参数,一个是一组图片资源,一个是动画执行时间,这个执行时间是所有帧执行的总时间.因此需要计算这两个参数.
图片的输入输出需要#import <ImageIO/ImageIO.h>这个头文件
计算上面两个参数,需要获取gif的图片资源文件,获取其相关属性.写了一个分类方法具体代码如下:
/**
承载gif内容的image对象
图片名称,一般不带后缀名
@param gifName gif图片名称
@return 承载gif内容的image对象
*/
+(UIImage *)imageNamedGifName:(NSString *)gifName{
//1.找到文件获取文件数据
if ([gifName hasSuffix:@".gif"]) {
gifName = [gifName stringByReplacingOccurrencesOfString:@".gif" withString:@""];
}
NSURL *url = [[NSBundle mainBundle] URLForResource:gifName withExtension:@".gif"];
NSData *data = [NSData dataWithContentsOfURL:url];
if (!data) {
return nil;
}
//2.获取文件资源 这里需要导入imageIO类
CGImageSourceRef sourceRef = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(sourceRef);
NSTimeInterval douration = 0;//存储gif动画总时间
NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];//储存的图片
for (size_t i = 0; i < count; i++) {
//获取每一张图片 并保存需要的信息
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(sourceRef, i, NULL);
if (imageRef) {
[images addObject:[UIImage imageWithCGImage:imageRef]];
NSDictionary *dict = (__bridge NSDictionary *) CGImageSourceCopyPropertiesAtIndex(sourceRef, i, NULL);
NSDictionary *gifPorperty = dict[(__bridge NSString *)kCGImagePropertyGIFDictionary];
NSNumber *unclampedDelayTime = gifPorperty[(__bridge NSString *)kCGImagePropertyGIFUnclampedDelayTime];
float thisDelyTime = 0;
if (unclampedDelayTime) {
thisDelyTime = unclampedDelayTime.floatValue;
}else{
NSNumber *delyTime = gifPorperty[(__bridge NSString *)kCGImagePropertyGIFDelayTime];
thisDelyTime = delyTime.floatValue;
}
//如果低于10ms 设置成100ms参考如下解释
// Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
// We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
// a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
// for more information.
if (thisDelyTime <= 0.001f) {
thisDelyTime = 0.1f;
}
douration += thisDelyTime;
}
CGImageRelease(imageRef);
}
CFRelease(sourceRef);
//获得最终图片
return [UIImage animatedImageWithImages:images duration:douration];;
}
网友评论