preface
Many projects need to load the GIF images, but there are many problems in use UIImageView directly loading, so to find information for a loading GIF Demo, thinking sources inside the link to https://github.com/YouXianMing/Animations The solution has been given. Demo just strips the functionality and encapsulates it.
Train of thought
Use FLAnimatedImage to load GIF images, use SDWebImage to do caching, without further ado, directly on the code.
Method of use
Import header file#import "GIFView.h" Create GIFView, added to the view on GIFView * view = [[GIFView alloc] initWithFrame: CGRectMake (0, 200, the self. The frame. The size, width, 300)]. view.url = @"http://upload-images.jianshu.io/upload_images/1979970-9d2b1cc945099612.gif? imageMogr2/auto-orient/strip";
[self.view addSubview:view];
Copy the code
GIFView internal code
@property (nonatomic,weak)FLAnimatedImageView *gifImageView; @end @implementation GIFView -(instancetype)initWithFrame:(CGRect)frame {if (self = [super initWithFrame:frame])
{
[self initUI];
}
returnself; } - (void)initUI {// Create FLAnimatedImageView from UIView FLAnimatedImageView *gifImageView = [[FLAnimatedImageView alloc] init]; gifImageView.frame = self.frame; [self addSubview:gifImageView]; _gifImageView = gifImageView; } -(void)setUrl:(NSString *)url { _url = url; / / convert GIF into Data NSData * gifImageData = [self imageDataFromDiskCacheWithKey: url]; // The sandbox exists, directly loading displayif(gifImageData) { [self animatedImageView:_gifImageView data:gifImageData]; // Sandbox does not exist, network fetch}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]; }); }]; }} // create GIF from data - (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; }]; } / / read from the sandbox - (NSData *) imageDataFromDiskCacheWithKey: (nsstrings *) key path = {nsstrings * [[[SDWebImageManager sharedManager] imageCache] defaultCachePathForKey:key];return [NSData dataWithContentsOfFile:path];
}
Copy the code
rendering
Note here to use the real machine test, simulator test will see the lag phenomenon
The statement
Here, just a simple stripping function, encapsulated, convenient for everyone to use. The Demo address is here, GIFDemo