iOS-FLAnimatedImage加载Gif

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];
    };
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容