iOS中有时候需要加载一些Gif动画图片,从实现方式和性能上考虑目前FLAnimatedImage比较适合.
基础实现
安装FLAnimatedImage第三方库,导入头文件FLAnimatedImage,加载Gif图片:
self.showBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
self.showBgView.center = self.view.center;
NSURL *imgUrl = [[NSBundle mainBundle] URLForResource:@"FlyElephant" withExtension:@"gif"];
FLAnimatedImage *animatedImg = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:imgUrl]];
self.animatedImgView = [[FLAnimatedImageView alloc] init];
self.animatedImgView.animatedImage = animatedImg;
self.animatedImgView.frame = CGRectMake(0,0,100,100);
[self.showBgView addSubview:self.animatedImgView];
[self.view addSubview:self.showBgView];
循环次数
实现之后发现Gif图片无限播放,如果想只播放一次,然后删除动画,有两种方式,一种是根据Gif的时间,定时删除,第二种通过FLAnimatedImageView提供的回调实现.
@interface FLAnimatedImageView : UIImageView
// Setting `[UIImageView.image]` to a non-`nil` value clears out existing `animatedImage`.
// And vice versa, setting `animatedImage` will initially populate the `[UIImageView.image]` to its `posterImage` and then start animating and hold `currentFrame`.
@property (nonatomic, strong) FLAnimatedImage *animatedImage;
@property (nonatomic, copy) void(^loopCompletionBlock)(NSUInteger loopCountRemaining);
@property (nonatomic, strong, readonly) UIImage *currentFrame;
@property (nonatomic, assign, readonly) NSUInteger currentFrameIndex;
// The animation runloop mode. Enables playback during scrolling by allowing timer events (i.e. animation) with NSRunLoopCommonModes.
// To keep scrolling smooth on single-core devices such as iPhone 3GS/4 and iPod Touch 4th gen, the default run loop mode is NSDefaultRunLoopMode. Otherwise, the default is NSDefaultRunLoopMode.
@property (nonatomic, copy) NSString *runLoopMode;
@end
动画播放完成之后删除动画的实现:
__weak typeof (self) weakSelf = self;
self.animatedImgView.loopCompletionBlock = ^(NSUInteger loopCountRemaining){
[weakSelf.showBgView removeFromSuperview];
};