Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Animate color change from color to color

Tags:

android

colors

Assuming I have two colors, and I need to create a real time animation that fastly switches from a color to another.

I tried just to increment the color hexadecimal until I reach the other, but that gave a really bad animation as it showed lots of unrelated colors.

I am using setColorFilter(color, colorfilter) to change the color of an imageview.

Changing the HUE will give me the best visual results? If so, how can I change it for a solid color?

SOLUTION: I solved it by recursively shifting hue

private int hueChange(int c,int deg){        float[] hsv = new float[3];       //array to store HSV values        Color.colorToHSV(c,hsv); //get original HSV values of pixel        hsv[0]=hsv[0]+deg;                //add the shift to the HUE of HSV array        hsv[0]=hsv[0]%360;                //confines hue to values:[0,360]        return Color.HSVToColor(Color.alpha(c),hsv);     } 
like image 632
zed Avatar asked Aug 13 '13 18:08

zed


People also ask

Which type of animation is used for animating the background color of a layout?

You can use new Property Animation Api for color animation: int colorFrom = getResources().


1 Answers

Combining @zed's and @Phil's answer gives a nice smooth transition using the ValueAnimator.

final float[] from = new float[3],               to =   new float[3];  Color.colorToHSV(Color.parseColor("#FFFFFFFF"), from);   // from white Color.colorToHSV(Color.parseColor("#FFFF0000"), to);     // to red  ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   // animate from 0 to 1 anim.setDuration(300);                              // for 300 ms  final float[] hsv  = new float[3];                  // transition color anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){     @Override public void onAnimationUpdate(ValueAnimator animation) {         // Transition along each axis of HSV (hue, saturation, value)         hsv[0] = from[0] + (to[0] - from[0])*animation.getAnimatedFraction();         hsv[1] = from[1] + (to[1] - from[1])*animation.getAnimatedFraction();         hsv[2] = from[2] + (to[2] - from[2])*animation.getAnimatedFraction();          view.setBackgroundColor(Color.HSVToColor(hsv));     } });  anim.start();                                         

The HSV will give a nicer transition than Androids default color space because HSV describes colors in cylindrical coordinates that nicely separate the color's properties and allow a smooth transition across a single axis. You can see from the image below that traveling along the H, S, or V directions gives a nice continuous transition between colors.

enter image description here

like image 89
bcorso Avatar answered Oct 07 '22 11:10

bcorso