Lottie Android: add color overlay to animation

SolveSoul picture SolveSoul · Apr 12, 2017 · Viewed 16.2k times · Source

I'm using Lottie for Android to add some animations in an app. In this app the primary and accent color can be chosen via the settings. I'm using an animation with a transparent background. To make the animation fit the chosen colors I'd like to add a color overlay to the animation, this way I can have one animation file but I can set the color programmatically.

Does anyone have an idea how I can manipulate the animation by adding a color overlay?

Answer

SolveSoul picture SolveSoul · Aug 10, 2017

To apply a color filter you'll need three things as of now:

  1. KeyPath (name of content you wish to edit)
  2. LottieProperty (name of property you wish to edit)
  3. LottieValueCallback (callback called for every animation re-render)

The layer name can be found in the JSON of the animation by the tag 'nm'.

Add a full color overlay:

LottieAnimationView animationView = findViewById(R.id.animation_view);
animationView.addValueCallback(
        new KeyPath("**"),
        LottieProperty.COLOR_FILTER,
        new SimpleLottieValueCallback<ColorFilter>() {
            @Override
            public ColorFilter getValue(LottieFrameInfo<ColorFilter> frameInfo) {
                return new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);
            }
        }
);

Add a single layer color overlay (layer called "checkmark"):

LottieAnimationView animationView = findViewById(R.id.animation_view);
animationView.addValueCallback(
        new KeyPath("checkmark", "**"),
        LottieProperty.COLOR_FILTER,
        new SimpleLottieValueCallback<ColorFilter>() {
            @Override
            public ColorFilter getValue(LottieFrameInfo<ColorFilter> frameInfo) {
                return new PorterDuffColorFilter(Color.CYAN, PorterDuff.Mode.SRC_ATOP);
            }
        }
);

Remove any color overlays:

LottieAnimationView animationView = findViewById(R.id.animation_view);
animationView.addValueCallback(new KeyPath("**"), LottieProperty.COLOR_FILTER,
        new SimpleLottieValueCallback<ColorFilter>() {
            @Override
            public ColorFilter getValue(LottieFrameInfo<ColorFilter> frameInfo) {
                return null;
            }
        }
);

You can read all about it in the official documentation.

You can also check out this sample repository

Here's a visual on the results of the code snippets:

Example