2015-01-05 4 views
0

Я пишу код, в котором необходимо изменить цвет фона с одного цвета на другой цвет по альфа-анимации.Изменить цвет с альфа-анимацией

Я попытался с

ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(stickyLayout, 
         "backgroundColor", 
         new ArgbEvaluator(), 
         0xFFFFFFFF, 
         0xff78c5f9); 

EDIT: Поскольку большинство из нас не ясно, Предположим, нам нужно изменить этот цвет с альфа на SeekBar обновленные значения выше упомянутой работе решение несколько, но не как ожидалось с альфа. ..любое предложение?

+0

Цвета вы используете имеют полный альфа 'ff' – Blackbelt

+0

Это может быть поможет вам: [Как сделать фон прозрачным 20% в android] (http://stackoverflow.com/a/16890937/2668136) – Fllo

+0

Это прекрасно ff и Fllo ... так как я хотел переместиться от полного белого до полного Dark, скажите 0xff78c5f9 ... любое предложение! – CoDe

ответ

0

Это работает код, который я нашел до сих пор:

/** 
    * Initialise header color while translate animation 
    */ 
    private void initHeaderColor(int startColor, int endColor) { 

     initR = Color.red(startColor); 
     initG = Color.green(startColor); 
     initB = Color.blue(startColor); 
     initAlpha = Color.alpha(startColor); 

     endR = Color.red(endColor); 
     endG = Color.green(endColor); 
     endB = Color.blue(endColor); 
     endAlpha = Color.alpha(endColor); 
    } 

и офсетная Вашего желания.

/** 
    * Translate header view component 
    * @param slideOffset 
    */ 
    private void translateHeaderView(float slideOffset) { 

      finalR = (int) (initR + (endR - initR) * slideOffset); 
      finalG = (int) (initG + (endG - initG) * slideOffset); 
      finalB = (int) (initB + (endB - initB) * slideOffset); 
      finalAlpha = (int) (initAlpha + (endAlpha - initAlpha) * slideOffset); 

      int color = Color.argb(finalAlpha, finalR, finalG, finalB); 
      fmActionBar.setBackgroundColor(color); 
     } 
0

Я использую статический вспомогательный метод для интерполяции двух цветов.

public static int interpolateColor(int colorA, int colorB, float proportion) { 
float[] hsva = new float[3]; 
float[] hsvb = new float[3]; 
Color.colorToHSV(colorA, hsva); 
Color.colorToHSV(colorB, hsvb); 
for (int i = 0; i < 3; i++) { 
    hsvb[i] = interpolate(hsva[i], hsvb[i], proportion); 
} 
int alpha1 = Color.alpha(colorA); 
int alpha2 = Color.alpha(colorB); 
int newAlpha = interpolate(alpha1, alpha2, proportion); 
return Color.HSVToColor(newAlpha, hsvb); } 

Также интерполировать Метод:

private static float interpolate(float a, float b, float proportion) { 
return (a + ((b - a) * proportion)); } 

Этот метод дает правильный цвет для значения пропорции betwenn 0-1, где 0 является Colora полностью видимым и 1 означает colorB полностью виден.

Затем вы можете использовать ValueAnimator, чтобы добавить onUpdateListener и получить анимациюPercentage и передать ее пропорционально методу интерполяции.

Как вы можете видеть, я добавил и альфа-значения в метод.

1

Вам не нужны эти методы: initHeaderColor & translateHeaderView.

Определить ArgbEvaluator в качестве члена класса: evaluate метода

ArgbEvaluator mArgbEvaluator; 

// define start & end colors 
int mStartColor, mEndColor; 

// initialize start & end colors 

Call ArgbEvaluator с параметрами (slideOffset, startColor, endColor), отлитые возвращаемое значение Integer, и использовать его, чтобы установить цвет фона fmActionBar:

void updateActionBarbgColor(float slideOffset) { 
    if (mArgbEvaluator == null) 
     mArgbEvaluator = new ArgbEvaluator(); 

    int bgColor = (Integer) mArgbEvaluator.evaluate(slideOffset, mStartColor, mEndColor); 
    fmActionBar.setBackgroundColor(bgColor); 
} 

Справочные, ArgbEvaluator#evaluate(...):

public Object evaluate(float fraction, Object startValue, Object endValue) { 
    int startInt = (Integer) startValue; 
    int startA = (startInt >> 24) & 0xff; 
    int startR = (startInt >> 16) & 0xff; 
    int startG = (startInt >> 8) & 0xff; 
    int startB = startInt & 0xff; 

    int endInt = (Integer) endValue; 
    int endA = (endInt >> 24) & 0xff; 
    int endR = (endInt >> 16) & 0xff; 
    int endG = (endInt >> 8) & 0xff; 
    int endB = endInt & 0xff; 

    return (int)((startA + (int)(fraction * (endA - startA))) << 24) | 
      (int)((startR + (int)(fraction * (endR - startR))) << 16) | 
      (int)((startG + (int)(fraction * (endG - startG))) << 8) | 
      (int)((startB + (int)(fraction * (endB - startB)))); 
} 
3
ValueAnimator colorAnim = ObjectAnimator.ofInt(**myView**, "backgroundColor", Color.RED, Color.BLUE); 
colorAnim.setDuration(3000); 
colorAnim.setEvaluator(new ArgbEvaluator()); 
colorAnim.setRepeatCount(ValueAnimator.INFINITE); 
colorAnim.setRepeatMode(ValueAnimator.REVERSE); 
colorAnim.start(); 

Где MyView это вид, на котором вы хотите применить анимацию

Смежные вопросы