關於gif的展現,有些項目中不多用到,因此有的人對於這方面瞭解不是不少web
下面介紹幾種展現gif的方法,但願你們能夠用得上,有更好的方法歡迎評論區留言瀏覽器
一,展現本地的gif,使用的SDWebImage裏面的方法:緩存
+ (UIImage *)sd_animatedGIFNamed:(NSString *)name; + (UIImage *)sd_animatedGIFWithData:(NSData *)data;
使用以後發現這個方法會使內存迅速上增300M,在網上找了一些方法:網絡
//在didReceiveMemoryWarning方法中釋放SDImage的緩存便可! - (void)didReceiveMemoryWarning { [superdidReceiveMemoryWarning]; // Dispose of any resources that can be recreated. [[SDWebImageManagersharedManager]cancelAll]; [[SDImageCachesharedImageCache]clearDisk]; }
可是使用以後可能效果並不明顯性能
二,展現本地的gif,使用 FLAnimatedImage動畫
FLAnimatedImage 是 iOS 的一個渲染 Gif 動畫的引擎。ui
功能:url
可同時播放多個 Gif.net
動畫,速度媲美桌面瀏覽器code
可變幀延遲
內存佔用小
可在第一次循環播放時消除或者阻止延遲
動畫的幀延遲解析性能媲美瀏覽器
示例代碼:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test_gif" ofType:@"gif"];
NSURL *url = [NSURL fileURLWithPath:filePath];
FLAnimatedImage *gest = [FLAnimatedImage animatedImageWithGIFData: [NSData dataWithContentsOfURL:url]];
FLAnimatedImageView *gestImageView = [[FLAnimatedImageView alloc] init];
gestImageView.animatedImage = gest;
gestImageView.frame = CGRectMake(461, 311, 119.5, 113);
[view addSubview:gestImageView];
--------------------
FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif"]]];
FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
imageView.animatedImage = image; imageView.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
[self.view addSubview:imageView];
三,利用很原始的方法展現固定的gif
將gif圖片分解成多張png圖片,使用UIImageView播放。這個是先讓ui作好連續的圖片,放到本地展現。
四,用webview展現
五,用傳統的方法偏c一點的,來直接展現本地gif
//1.加載Gif圖片,轉換成Data類型
NSString *path = [NSBundle.mainBundle pathForResource:@"demo" ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
//2.將data數據轉換成CGImageSource對象
CGImageSourceRef imageSource = CGImageSourceCreateWithData(CFBridgingRetain(data), nil);
size_t imageCount = CGImageSourceGetCount(imageSource);
//3.遍歷全部圖片
NSMutableArray *images = [NSMutableArray array];
NSTimeInterval totalDuration = 0;
for (int i = 0; i<imageCount; i++) {
//取出每一張圖片
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil);
UIImage *image = [UIImage imageWithCGImage:cgImage];
[images addObject:image];
//持續時間
NSDictionary *properties = (__bridge_transfer NSDictionary*)CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil);
NSDictionary *gifDict = [properties objectForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
NSNumber *frameDuration =
[gifDict objectForKey:(__bridge NSString *)kCGImagePropertyGIFDelayTime];
totalDuration += frameDuration.doubleValue;
}
//4.設置imageView屬性
self.imageView.animationImages = images;
六,加載網絡gif
直接使用sdweb的setimageWithUrl: 就行
參考連接:
https://blog.csdn.net/dolacmeng/article/details/81223612
https://blog.csdn.net/dolacmeng/article/details/81223612