美文网首页
iOS Lottie 使用注意点

iOS Lottie 使用注意点

作者: SpringAlways | 来源:发表于2020-04-17 08:16 被阅读0次

lottie是一个很不错的库,能够用设计人员出动画,直接内嵌程序进行播放,酷炫而简单,大大提升开发效率。
不过iOS版本的api有一些不太友好,有两个点记录一下

  • LOTAnimationView 支持重复播放,但是每一次重复播放后没有调用时机。究其原因是因为animation.repeatCount = _loopAnimation ? HUGE_VALF : 1; 重复播放是把repeatCount设为了无限大

  • LOTAnimationView 不支持设置播放几次,每次的播放完成的callback时机。原因同上。解决办法是在- (void)playWithCompletion:(LOTAnimationCompletionBlock)completion这个函数可以在回调中再开启来实现。前提得把loopAnimation关掉

  • lottie动画在组件中实现,并且有图片依赖,需要把图片和json文件放到同一个目录下,并且提供该目录的bundle.
    姿势一:

- (NSBundle *)bundleWithRelativeRootPath:(NSString *)path
{
    NSString *lightBundleStr        = @"/XXX.bundle";
    NSString *pathBundleStr         = [[NSBundle bundleForClass:[self class]].resourcePath stringByAppendingPathComponent:[lightBundleStr stringByAppendingPathComponent:path]];
    NSBundle *pathBundle            = [NSBundle bundleWithPath:pathBundleStr];
    NSAssert(pathBundle != nil, @"bundle路径不对,请检查!");
    return pathBundle;
}

//然后调用下面的方法
+ (nonnull instancetype)animationNamed:(nonnull NSString *)animationName inBundle:(nonnull NSBundle *)bundle NS_SWIFT_NAME(init(name:bundle:));
+ (nonnull instancetype)animationFromJSON:(nullable NSDictionary *)animationJSON inBundle:(nullable NSBundle *)bundle NS_SWIFT_NAME(init(json:bundle:));


姿势二:

- (nonnull instancetype)initWithModel:(nullable LOTComposition *)model inBundle:(nullable NSBundle *)bundle;

在创建LOTComposition的之后,还可以指定根目录,这样就可以使用同一个bundle了。

- (void)setRootDirectory:(NSString *)rootDirectory {
    _rootDirectory = rootDirectory;
    self.assetGroup.rootDirectory = rootDirectory;
}
但要记得这个setroot要在initWithModel之前设置!

因为initModel会触发整个json文件的读取和ui元素初始化,包括图片初始化。初始化之后再设置root就没有任何意义了。
两个姿势供你挑选。其实关系也不大,一个是维护bundle的目录,一个是维护root的目录,半斤八两。

有的同学会问:我也在组件中使用lottie啊,怎么没涉及到bundle设置的问题?
答:因为bundle只用来获取资源,如果你使用json直传的方式,并且没有需要依赖的图片,那么不会影响lottie内部的加载。

- (void)_mapFromJSON:(NSDictionary *)jsonDictionary
     withAssetBundle:(NSBundle *)bundle {
//省略无关
    NSArray *assetArray = jsonDictionary[@"assets"];
    if (assetArray.count) {
        _assetGroup = [[LOTAssetGroup alloc] initWithJSON:assetArray withAssetBundle:bundle withFramerate:_framerate];
    }
  //省略无关
}

相关文章

网友评论

      本文标题:iOS Lottie 使用注意点

      本文链接:https://www.haomeiwen.com/subject/fdpsvhtx.html