android color between two colors, based on percentage?

后端 未结 9 1828
悲哀的现实
悲哀的现实 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:34

    I just wanted to update Mark Renouf's answer to handle alpha channel as well:

    private float interpolate(float a, float b, float proportion) {
        return (a + ((b - a) * proportion));
    }
    
    /**
     * Returns an interpolated color, between a and b
     * proportion = 0, results in color a
     * proportion = 1, results in color b
     */
    private int interpolateColor(int a, int b, float proportion) {
    
        if (proportion > 1 || proportion < 0) {
            throw new IllegalArgumentException("proportion must be [0 - 1]");
        }
        float[] hsva = new float[3];
        float[] hsvb = new float[3];
        float[] hsv_output = new float[3];
    
        Color.colorToHSV(a, hsva);
        Color.colorToHSV(b, hsvb);
        for (int i = 0; i < 3; i++) {
            hsv_output[i] = interpolate(hsva[i], hsvb[i], proportion);
        }
    
        int alpha_a = Color.alpha(a);
        int alpha_b = Color.alpha(b);
        float alpha_output = interpolate(alpha_a, alpha_b, proportion);
    
        return Color.HSVToColor((int) alpha_output, hsv_output);
    }
    

提交回复
热议问题