android color between two colors, based on percentage?

后端 未结 9 1837
悲哀的现实
悲哀的现实 2020-11-29 23:17

I would like to calculate the color depending on a percentage value:

float percentage = x/total;
int color;
if (percentage >= 0.95) {
  color = Color.GREE         


        
9条回答
  •  没有蜡笔的小新
    2020-11-29 23:41

    Some of solutions of this thread didn't work for me, so I create another solution. Maybe it is useful for someone.

    /**
     * Get the color between two given colors
     * @param colorStart int color start of degradate
     * @param colorEnd int color end of degradate
     * @param percent int percent to apply (0 to 100)
     * @return int color of degradate for given percent
     */
    public static int getColorOfDegradate(int colorStart, int colorEnd, int percent){
        return Color.rgb(
                getColorOfDegradateCalculation(Color.red(colorStart), Color.red(colorEnd), percent),
                getColorOfDegradateCalculation(Color.green(colorStart), Color.green(colorEnd), percent),
                getColorOfDegradateCalculation(Color.blue(colorStart), Color.blue(colorEnd), percent)
        );
    }
    
    private static int getColorOfDegradateCalculation(int colorStart, int colorEnd, int percent){
        return ((Math.min(colorStart, colorEnd)*(100-percent)) + (Math.max(colorStart, colorEnd)*percent)) / 100;
    }
    

提交回复
热议问题