Created
November 28, 2014 14:47
-
-
Save martintreurnicht/f6bbb20a43211bc2060e to your computer and use it in GitHub Desktop.
Lighten and darken colors in android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int lighten(int color, double fraction) { | |
int red = Color.red(color); | |
int green = Color.green(color); | |
int blue = Color.blue(color); | |
red = lightenColor(red, fraction); | |
green = lightenColor(green, fraction); | |
blue = lightenColor(blue, fraction); | |
int alpha = Color.alpha(color); | |
return Color.argb(alpha, red, green, blue); | |
} | |
public static int darken(int color, double fraction) { | |
int red = Color.red(color); | |
int green = Color.green(color); | |
int blue = Color.blue(color); | |
red = darkenColor(red, fraction); | |
green = darkenColor(green, fraction); | |
blue = darkenColor(blue, fraction); | |
int alpha = Color.alpha(color); | |
return Color.argb(alpha, red, green, blue); | |
} | |
private static int darkenColor(int color, double fraction) { | |
return (int)Math.max(color - (color * fraction), 0); | |
} | |
private static int lightenColor(int color, double fraction) { | |
return (int) Math.min(color + (color * fraction), 255); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure this works very well since the r/g/b values are not linearly correlated to their intensity. See https://en.wikipedia.org/wiki/SRGB