1. 程式人生 > >Android之Color 顏色過度計算

Android之Color 顏色過度計算

在看自定義TypeEvaluator來計算屬性動畫的屬性值時,用到了對顏色的過度計算,翻看了好多部落格,找到了比較有優秀的解決方案,在此記錄,以備後用。

/**
 * 根據fraction值來計算當前的顏色。
 */
private int getCurrentColor(float fraction, int startColor, int endColor) {
    int redCurrent;
    int blueCurrent;
    int greenCurrent;
    int alphaCurrent;

    int redStart = Color.red(startColor);
    int blueStart = Color.blue(startColor);
    int greenStart = Color.green(startColor);
    int alphaStart = Color.alpha(startColor);

    int redEnd = Color.red(endColor);
    int blueEnd = Color.blue(endColor);
    int greenEnd = Color.green(endColor);
    int alphaEnd = Color.alpha(endColor);

    int redDifference = redEnd - redStart;
    int blueDifference = blueEnd - blueStart;
    int greenDifference = greenEnd - greenStart;
    int alphaDifference = alphaEnd - alphaStart;

    redCurrent = (int) (redStart + fraction * redDifference);
    blueCurrent = (int) (blueStart + fraction * blueDifference);
    greenCurrent = (int) (greenStart + fraction * greenDifference);
    alphaCurrent = (int) (alphaStart + fraction * alphaDifference);

    return Color.argb(alphaCurrent, redCurrent, greenCurrent, blueCurrent);
}

這裡寫圖片描述