Skip to content

Instantly share code, notes, and snippets.

@mikeseif
Last active August 29, 2015 14:06
Show Gist options
  • Save mikeseif/57c83e3e0bd2eb2bb0e0 to your computer and use it in GitHub Desktop.
Save mikeseif/57c83e3e0bd2eb2bb0e0 to your computer and use it in GitHub Desktop.
Desaturate the given Color int by the ratio provided, 1.0f for full saturation, 0.0f for max desaturation. Edit the minimum value of 0.2f (or add as an additional param) to alter how low the desaturation can go.
/**
* Desaturate the given color int value by the provided ratio, down to a minimum of 0.2f.
*
* Note: Do not pass R.color ints, resolve the actual color int via
* getResources().getColor(R.color.your_color_name_here).
*
* f(x) = ( startSaturation / 1.0f * ratio ) + ( minSaturation * (1.0f - ratio) )
*
* @param int The color value to desaturate
* @param float The ratio to desatrate by (0.0f - 1.0f)
*
* @return int the desaturated color value
*/
public static int desaturateColor(int color, float ratio) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[1] = ( hsv[1] / 1 * ratio ) + ( 0.2f * (1.0f - ratio) );
return Color.HSVToColor(hsv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment