能否通过编程重新着色 Lottie 动画?

5
如果我有一个Lottie动画,形式为json文件,是否可以通过代码或在json文件本身中重新着色?
(明确一下,我希望有一种方法可以在不涉及After Effects的情况下完成。例如,如果我决定更改应用程序的主要颜色,整个应用程序将会改变,除非有一种方法可以实现这一点)
3个回答

4

我搞定了。以这个例子为例,假设我想将特定的图层重新着色为Color.RED。

您需要使用LottieAnimationView、KeyPath和LottieValueCallback。

private LottieAnimationView lottieAnimationVIew;
private KeyPath mKeyPath;
private LottieValueCallback<Integer> mCallback;

在你的onCreate方法(或者对于一个fragment是在onViewCreated方法中),你会通过findViewById获取到动画,并使用"addLottieOnCompositionLoadedListener"来给lottieAnimationView设置监听器,在里面你需要设置"mKeyPath"和"mCallback":

lottieAnimationVIew = findViewById(R.id.animationView);

lottieAnimationView.addLottieOnCompositionLoadedListener(new LottieOnCompositionLoadedListener() {
  @Override
  public void onCompositionLoaded(LottieComposition composition) {
    mKeyPath = getKeyPath(); // This is your own method for getting the KeyPath you desire. More on that below.
    mCallback = new LottieValueCallback<>();
    mCallback.setValue(Color.RED);
    checkBox.addValueCallback(mKeyPath, LottieProperty.COLOR, mCallback);
  }
});

参数"LottieProperty.COLOR"指定我要更改的属性。

可能有更好的方法,但这是我用于查找想要更改的特定项的"getKeyPath"方法。它会记录每个KeyPath,以便您可以看到您想要的哪一个。然后,在您提供正确的索引后,它将返回该项。我发现我想要的是列表中的第5个,因此硬编码索引为4。

private KeyPath getKeyPath() {
  List<KeyPath> keyPaths = lottieAnimationView.resolveKeyPath(new KeyPath("Fill", "Ellipse 1", "Fill 1"));
        
  for (int i = 0; i < keyPaths.size(); i++) {
    Log.i("KeyPath", keyPaths.get(i).toString());
  }
        
  if (keyPaths.size() == 5) {
    return keyPaths.get(4);
  }
  else {
    return null;
  }
}

请注意,"Fill"、"Ellipse 1"、"Fill 1"是我提供的字符串,以缩小列表范围,只列出具有这些键的图层,因为我知道我想要的图层在其中之一。可能还有更好的方法。

2
这是一个Kotlin的解决方案,适用于您可能遇到的所有情况:
/**sets tint for the animation.
 * @itemsToTint the items elements ("nm" inside "layers") the animation to tint.
 * null will reset all tinting. Empty will set tint for all. */
fun LottieAnimationView.setAnimationTint(itemsToTint: Array<String>?, @ColorInt color: Int) {
    //based on https://dev59.com/PFcQ5IYBdhLWcg3wEPsK#45607292 https://airbnb.io/lottie/#/android?id=dynamic-properties https://github.com/SolveSoul/lottie-android-colorfilter-sample
    if (itemsToTint == null) {
        //un-tint
        addValueCallback(KeyPath("**"), LottieProperty.COLOR_FILTER) { null }
        return
    }
    addValueCallback(
            KeyPath(*itemsToTint,"**" ),
            LottieProperty.COLOR_FILTER
    ) { PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP) }
}

0

这个主题上已经有另一个线程采用了相同的方法,但是更加简化: 如何在Lottie动画中添加颜色叠加层?

这里直接给出了一个例子(Kotlin):

        yourLottieAnimation.addValueCallback(
        KeyPath("whatever_keypath", "**"),
        LottieProperty.COLOR_FILTER
    ) {
        PorterDuffColorFilter(
            Color.CYAN,
            PorterDuff.Mode.SRC_ATOP
        )
    }

你也可以在 Lottie 编辑器中找到关键路径的名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接