Utility Function of the Day
The following method mixes several colors together according to a specified bias thus creating a new color. It is a very useful function for custom user-interface components, especially if they are to be affected by user-customization.
For example:
Consider a calendar-widget that has different color codes for different types of holidays (by religion perhaps). You can use this function to calculate the selection color for a specific day by mixing the global (user-chosen?) selection color with the specific day's color and even to go further and to mix several colors when holidays intersect.
How it works:
The specified Color objects are split to their individual color-components or channels (red, gree, blue and alpha) which are then collected while being multiplied by the per-color bias. Then, an average value for each color component is calculated based on the collected channels and used to create a new Color object.
Note:
Make sure to remember to cache the resulting Color object for re-use whenever possible! Object-Creation-Is-Expensive(tm).
The Code:
public static Color mixColors(Color[] colorsToMix, float[] colorBias)
{
long red = 0;
long green = 0;
long blue = 0;
long alpha = 0;
for (int i = 0; i < colorsToMix.length; i++)
{
Color currentColor = colorsToMix[i];
float currentBias = colorBias[i];
red += currentColor.getRed() * currentBias;
green += currentColor.getGreen() * currentBias;
blue += currentColor.getBlue() * currentBias;
alpha += currentColor.getAlpha() * currentBias;
}
red /= colorsToMix.length;
green /= colorsToMix.length;
blue /= colorsToMix.length;
alpha /= colorsToMix.length;
return new Color((int)red, (int)green, (int)blue, (int)alpha);
};
Enjoy!
0 Comments:
Post a Comment
<< Home