ios如何加載gif圖片
直接使用SDWebImage第三方庫就可以了
這里主要使用了UIImage的類方法
+ (nullable UIImage *)animatedImageWithImages:(NSArray<UIImage *> *)images duration:(NSTimeInterval)duration NS_AVAILABLE_IOS(5_0);
需要兩個參數,一個是一組圖片資源,一個是動畫執(zhí)行時間,這個執(zhí)行時間是所有幀執(zhí)行的總時間.因此需要計算這兩個參數.
圖片的輸入輸出需要#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];;
}