Android Color Average average(int color, int color2)

Here you can find the source of average(int color, int color2)

Description

Returns the a color created by an average between two colors.

Parameter

Parameter Description
color a parameter
color2 a parameter

Declaration

public static int average(int color, int color2) 

Method Source Code

//package com.java2s;

public class Main {
    /**//  w  w  w  .  jav  a 2  s . com
     * Returns the a color created by an average between two colors. For instance, if passed
     * black (0xff000000) and white (0xffffffff), will result in grey (0xff888888). Good for easy
     * color mixing.
     *
     * @param color
     * @param color2
     * @return
     */
    public static int average(int color, int color2) {

        final int[] parts1 = getArgb(color);
        final int[] parts2 = getArgb(color2);

        for (int i = 0; i < parts1.length; i++) {

            parts1[i] = (int) ((float) (parts1[i] + parts2[i]) / 2f);
        }

        return getColorFromArgb(parts1);
    }

    /**
     * Gets an ARGB int array from a provided color
     *
     * @param color
     * @return
     */
    public static int[] getArgb(int color) {
        final int a = (color >>> 24);
        final int r = (color >> 16) & 0xFF;
        final int g = (color >> 8) & 0xFF;
        final int b = (color) & 0xFF;

        return new int[] { ClippedColorPart(a), ClippedColorPart(r),
                ClippedColorPart(g), ClippedColorPart(b) };
    }

    /**
     * Gets an int color from an int[4] containing argb values.
     * @param argb
     * @return an int containing the result color
     */
    public static int getColorFromArgb(int[] argb) {

        if (argb.length != 4) {
            throw new IllegalArgumentException(
                    "ARGB int array must have a length of 4.");
        }

        return (ClippedColorPart(argb[0]) << 24)
                + (ClippedColorPart(argb[1]) << 16)
                + (ClippedColorPart(argb[2]) << 8)
                + (ClippedColorPart(argb[3]));
    }

    public static int ClippedColorPart(int color) {
        if (color < 0) {
            return 0;
        } else if (color > 0xFF) {
            return 0xFF;
        }
        return color;
    }
}

Related

  1. averageBlendTwoColors(int c1, int c2)
  2. multiplyBlendTwoColors(int c1, int c2)