本文整理了 iOS 中展示 GIF 動態圖的幾種常見做法,涵蓋系統原生 API 與主流第三方庫,供大家參考。
特點:加載耗時略長,但性能表現更穩,播放 GIF 的流暢度更好。
// 動態展示 GIF 圖片 - WebView
-(void)showGifImageWithWebView{
// 讀取 gif 圖片數據
NSData *gifData = [NSData dataWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"]];
// 生成 UIWebView
UIWebView *imageWebView = [[UIWebView alloc] initWithFrame:CGRectMake(112, 302, 132, 102)];
// 用戶不可交互
imageWebView.userInteractionEnabled = NO;
// 加載 gif 數據
[imageWebView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
// 添加到視圖
[self.view addSubview:imageWebView];
}
加載速度更快,性能不如 UIWebView,但優點是易於擴展。做法有兩步:先給 UIImageView 加一個 Category,封裝解析與播放兩個方法。
UIImage+Tool.h:
#import <UIKit/UIKit.h>
@interface UIImageView (Tool)
/** 解析 gif 文件數據的方法,block 中會把解析結果傳出來 */
-(void)getGifImageWithUrk:(NSURL *)url returnData:(void(^)(NSArray<UIImage *> * imageArray,
NSArray<NSNumber *> * timeArray,
CGFloat totalTime,
NSArray<NSNumber *> * widths,
NSArray<NSNumber *> * heights))dataBlock;
/** 為 UIImageView 添加一個設置 gif 內容的方法 */
-(void)yh_setImage:(NSURL *)imageUrl;
@end
UIImageView+Tool.m:
//
// UIImageView+Tool.m
//
// Created by qiuxuewei on 16/3/2.
// Copyright © 2016年 邱學偉. All rights reserved.
//
#import "UIImageView+Tool.h"
// 要引入 ImageIO 庫
#import <ImageIO/ImageIO.h>
@implementation UIImageView (Tool)
// 解析 gif 文件數據的方法,block 中會把解析結果傳出來
-(void)getGifImageWithUrk:(NSURL *)url returnData:(void(^)(NSArray<UIImage *> * imageArray,
NSArray<NSNumber *> * timeArray,
CGFloat totalTime,
NSArray<NSNumber *> * widths,
NSArray<NSNumber *> * heights))dataBlock{
// 通過文件 url 把 gif 讀取為圖片數據引用
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
// 獲取 gif 文件中圖片的個數
size_t count = CGImageSourceGetCount(source);
// 記錄 gif 播放一輪的時間
float allTime = 0;
NSMutableArray * imageArray = [[NSMutableArray alloc] init]; // 存放所有圖片
NSMutableArray * timeArray = [[NSMutableArray alloc] init]; // 存放每一幀的播放時間
NSMutableArray * widthArray = [[NSMutableArray alloc] init]; // 存放每張圖的寬度
NSMutableArray * heightArray = [[NSMutableArray alloc] init]; // 存放每張圖的高度
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
[imageArray addObject:(__bridge UIImage *)(image)];
CGImageRelease(image);
// 獲取圖片信息
NSDictionary * info = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
CGFloat width = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelWidth] floatValue];
CGFloat height = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelHeight] floatValue];
[widthArray addObject:[NSNumber numberWithFloat:width]];
[heightArray addObject:[NSNumber numberWithFloat:height]];
NSDictionary * timeDic = [info objectForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
CGFloat time = [[timeDic objectForKey:(__bridge NSString *)kCGImagePropertyGIFDelayTime] floatValue];
allTime += time;
[timeArray addObject:[NSNumber numberWithFloat:time]];
}
dataBlock(imageArray, timeArray, allTime, widthArray, heightArray);
}
// 為 UIImageView 添加一個設置 gif 內容的方法
-(void)yh_setImage:(NSURL *)imageUrl{
__weak id __self = self;
[self getGifImageWithUrk:imageUrl returnData:^(NSArray<UIImage *> *imageArray,
NSArray<NSNumber *> *timeArray,
CGFloat totalTime,
NSArray<NSNumber *> *widths,
NSArray<NSNumber *> *heights) {
// 添加幀動畫
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
NSMutableArray * times = [[NSMutableArray alloc] init];
float currentTime = 0;
// 設置每一幀的時間占比
for (int i = 0; i < imageArray.count; i++) {
[times addObject:[NSNumber numberWithFloat:currentTime / totalTime]];
currentTime += [timeArray[i] floatValue];
}
[animation setKeyTimes:times];
[animation setValues:imageArray];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
animation.repeatCount = MAXFLOAT; // 循環播放
animation.duration = totalTime; // 播放總時長
// Layer 層添加動畫
[[(UIImageView *)__self layer] addAnimation:animation forKey:@"gifAnimation"];
}];
}
@end
使用時導入頭文件即可:
#import "UIImageView+Tool.h"
-(void)showGifImageWithImageView{
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(112, 342, 132, 102)];
NSURL * url = [[NSURL alloc] initFileURLWithPath:
[[NSBundle mainBundle] pathForResource:@"earthGif.gif" ofType:nil]];
[imageView yh_setImage:url];
[self.view addSubview:imageView];
}
項目地址:https://github.com/liyong03/YLGIFImage
#import "YLGIFImage.h"
#import "YLImageView.h"
-(void)showGifImageWithYLImageView{
YLImageView * imageView = [[YLImageView alloc] initWithFrame:CGRectMake(112, 342, 132, 102)];
CGFloat centerX = self.view.center.x;
[imageView setCenter:CGPointMake(centerX, 402)];
[self.view addSubview:imageView];
imageView.image = [YLGIFImage imageNamed:@"earthGif.gif"];
}
項目地址:https://github.com/Flipboard/FLAnimatedImage
-(void)showGifImageWithFLAnimatedImage{
// GIF 路徑
NSString *pathForFile = [[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"];
// 轉成 NSData
NSData *dataOfGif = [NSData dataWithContentsOfFile:pathForFile];
// 初始化 FLAnimatedImage 對象
FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:dataOfGif];
// 初始化 FLAnimatedImageView 對象
FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
imageView.animatedImage = image;
imageView.frame = CGRectMake(112, 342, 132, 102);
[self.view addSubview:imageView];
}
以上就是本文的全部內容,希望對大家的學習有所幫助。