Android颜色计算

· 316字 · 2分钟
/**
 * 合并颜色,支持argb8888 
 * @param fg 前景色
 * @param bg 背景色
 */
 public static int blendColor(int fg, int bg) {
 int scr = Color.red(fg);
 int scg = Color.green(fg);
 int scb = Color.blue(fg);
 int sa = fg >>> 24;
 int dcr = Color.red(bg);
 int dcg = Color.green(bg);
 int dcb = Color.blue(bg);
 int color_r = dcr * (0xff - sa) / 0xff + scr * sa / 0xff;
 int color_g = dcg * (0xff - sa) / 0xff + scg * sa / 0xff;
 int color_b = dcb * (0xff - sa) / 0xff + scb * sa / 0xff;
 return ((color_r << 16) + (color_g << 8) + color_b) | (0xff000000);
}
    /** Calculates the constrast between two colors, using the algorithm provided by the WCAG v2. */
    public static float computeContrastBetweenColors(int bg, int fg) {
        float bgR = Color.red(bg) / 255f;
        float bgG = Color.green(bg) / 255f;
        float bgB = Color.blue(bg) / 255f;
        bgR = (bgR < 0.03928f) ? bgR / 12.92f : (float) Math.pow((bgR + 0.055f) / 1.055f, 2.4f);
        bgG = (bgG < 0.03928f) ? bgG / 12.92f : (float) Math.pow((bgG + 0.055f) / 1.055f, 2.4f);
        bgB = (bgB < 0.03928f) ? bgB / 12.92f : (float) Math.pow((bgB + 0.055f) / 1.055f, 2.4f);
        float bgL = 0.2126f * bgR + 0.7152f * bgG + 0.0722f * bgB;
        
        float fgR = Color.red(fg) / 255f;
        float fgG = Color.green(fg) / 255f;
        float fgB = Color.blue(fg) / 255f;
        fgR = (fgR < 0.03928f) ? fgR / 12.92f : (float) Math.pow((fgR + 0.055f) / 1.055f, 2.4f);
        fgG = (fgG < 0.03928f) ? fgG / 12.92f : (float) Math.pow((fgG + 0.055f) / 1.055f, 2.4f);
        fgB = (fgB < 0.03928f) ? fgB / 12.92f : (float) Math.pow((fgB + 0.055f) / 1.055f, 2.4f);
        float fgL = 0.2126f * fgR + 0.7152f * fgG + 0.0722f * fgB;
 
        return Math.abs((fgL + 0.05f) / (bgL + 0.05f));
    }
	//判断是否是深色
	isDark = computeContrastBetweenColors(color,Color.WHITE) > 3f;
comments powered by Disqus