iOS中有時(shí)候需要加載一些Gif動畫圖片,從實(shí)現(xiàn)方式和性能上考慮目前FLAnimatedImage比較適合.
基礎(chǔ)實(shí)現(xiàn)
安裝FLAnimatedImage第三方庫,導(dǎo)入頭文件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];
循環(huán)次數(shù)
實(shí)現(xiàn)之后發(fā)現(xiàn)Gif圖片無限播放,如果想只播放一次,然后刪除動畫,有兩種方式,一種是根據(jù)Gif的時(shí)間,定時(shí)刪除,第二種通過FLAnimatedImageView提供的回調(diào)實(shí)現(xiàn).
@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
動畫播放完成之后刪除動畫的實(shí)現(xiàn):
__weak typeof (self) weakSelf = self;
self.animatedImgView.loopCompletionBlock = ^(NSUInteger loopCountRemaining){
[weakSelf.showBgView removeFromSuperview];
};