前言
許多專案需要載入GIF圖片,但是在直接使用UIImageView載入存在許多問題,於是查詢資料做了一個載入GIF的Demo,思路來源https://github.com/YouXianMing/Animations 在連結裡邊,已經給出瞭解決辦法,Demo只是將功能剝離,簡單封裝了一下。
思路
使用FLAnimatedImage來載入GIF圖片,再利用SDWebImage來做快取,話不多說,直接上程式碼。
使用方法
匯入標頭檔案#import "GIFView.h"
建立GIFView,新增到檢視上
GIFView *view = [[GIFView alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 300)];
view.url = @"http://upload-images.jianshu.io/upload_images/1979970-9d2b1cc945099612.gif?imageMogr2/auto-orient/strip";
[self.view addSubview:view];
複製程式碼
GIFView內部程式碼
@interface GIFView()
/**GIF檢視*/
@property (nonatomic,weak)FLAnimatedImageView *gifImageView;
@end
@implementation GIFView
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self initUI];
}
return self;
}
- (void)initUI
{
//建立FLAnimatedImageView,繼承自UIView
FLAnimatedImageView *gifImageView = [[FLAnimatedImageView alloc] init];
gifImageView.frame = self.frame;
[self addSubview:gifImageView];
_gifImageView = gifImageView;
}
-(void)setUrl:(NSString *)url
{
_url = url;
//將GIF轉換成Data
NSData *gifImageData = [self imageDataFromDiskCacheWithKey:url];
//沙盒存在,直接載入顯示
if (gifImageData)
{
[self animatedImageView:_gifImageView data:gifImageData];
//沙盒不存在,網路獲取
} else
{
__weak __typeof(self) weakSelf = self;
NSURL *newUrl = [NSURL URLWithString:url];
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:newUrl
options:0
progress:nil
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
[[[SDWebImageManager sharedManager] imageCache] storeImage:image
recalculateFromImage:NO
imageData:data
forKey:newUrl.absoluteString
toDisk:YES];
//主執行緒顯示
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf animatedImageView:_gifImageView data:data];
});
}];
}
}
//通過資料建立GIF
- (void)animatedImageView:(FLAnimatedImageView *)imageView data:(NSData *)data
{
FLAnimatedImage *gifImage = [FLAnimatedImage animatedImageWithGIFData:data];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
imageView.animatedImage = gifImage;
imageView.alpha = 0.f;
[UIView animateWithDuration:1.f animations:^{
imageView.alpha = 1.f;
}];
}
//從沙盒讀取
- (NSData *)imageDataFromDiskCacheWithKey:(NSString *)key
{
NSString *path = [[[SDWebImageManager sharedManager] imageCache] defaultCachePathForKey:key];
return [NSData dataWithContentsOfFile:path];
}
複製程式碼
效果圖
這裡需要注意要用真機測試,模擬器測試會看到卡頓現象
宣告
在這裡說明下,只是簡單的剝離功能,封裝了一下,方便大家使用。Demo地址在這裡GIFDemo