Inverting colors (negative) using ColorMatrixColorFilter

2.7k Views Asked by At

I want to invert colors of black and white image and present that inversion as animation. Animation should go from white background to black (black background white car), and then revert back to white (white background, black car). You can see images here: enter image description here animated

I tried to use ColorMatrixColorFilter like this:

final ValueAnimator colorAnim = ValueAnimator.ofInt(0, 255);
    colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            int color = (int) animation.getAnimatedValue();
            float[] NEGATIVE = {
                    -1.0f, 0, 0, 0, color, // red
                    0, -1.0f, 0, 0, color, // green
                    0, 0, -1.0f, 0, color, // blue
                    0, 0, 0, 1.0f, 1  // alpha
            };
            v.setColorFilter(new ColorMatrixColorFilter(NEGATIVE));
        }
    });

But it won't return to default image (white background, black car). Calculation is not good. How to calculate proper values?

I tried to find how to do this, but I did not find anything useful.

Thanks!

1

There are 1 best solutions below

0
VC.One On

Did you try :

1) From loaded image, create two bitmap copies into variables eg: bmp_original and bmp_negative.

2) Apply the ColorMatrix to the bitmap called bmp_negative.

3) Create a function that fades between the two bitmaps (or fades their containers).

This is better than trying to recover original colours via ColorMatrix (wrong tool). For inverted colours it's better to use a For loop to check and change the RGB values of each pixel.

In the end, it is easier and more efficient to keep a copy of original and flip between original and effected, than to try and re-calculate original colors (which you already had before the effect).