iOS-FLAnimatedImage加载Gif

本文介绍了在iOS开发中如何利用FLAnimatedImage库来加载和显示Gif动画图片,并提供了详细的基础实现代码。同时,讨论了如何设置循环次数,通过设置loopCompletionBlock回调实现在Gif播放完成后的删除操作,确保动画只播放一次。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];
    };



转载链接:https://www.jianshu.com/p/9e0f594d704c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值