Android Studio 有没有可能通过编程的方式给一个乐透动画重新着色?

xriantvc  于 2023-04-07  发布在  Android
关注(0)|答案(3)|浏览(176)

如果我有一个json文件形式的lottie动画,有没有办法在代码中甚至在json本身中重新着色?
(To我希望有一种方法可以做到这一点,而不涉及After Effects。例如,如果我决定改变我的应用程序的主要颜色,整个应用程序将改变,除了动画,除非有一种方法可以做到这一点。

5jdjgkvh

5jdjgkvh1#

在这个例子中,假设我想将一个特定的图层重新着色为Color.RED。
您需要LottieAnimationView、KeyPath和LottieValueCallback

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

然后在onCreate(或onViewCreated)中,您将获得带有findViewById的动画,以及lottieAnimationView的“addLottieOnCompositionLoadedListener”,其中您将设置“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”是我提供的字符串,用于将列表缩小到仅具有这些键的那些,因为我知道我想要的层将在这些层中。可能还有更好的方法来做到这一点。

zf9nrax1

zf9nrax12#

关于这个主题还有另一个线程,它采用了相同的方法,但有点简化:How to add a color overlay to an animation in Lottie?
下面是一个例子(Kotlin):

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

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

jv4diomz

jv4diomz3#

以下是一个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://stackoverflow.com/a/45607292/878126 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) }
}

相关问题