iOS Lottie 使用注意点

2020-04-17  本文已影响0人  SpringAlways

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

- (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];
    }
  //省略无关
}
上一篇 下一篇

猜你喜欢

热点阅读