Reputation: 4487
Here is how I get a Lighter color given an int. But I am wondering how can I convert this to give me a darker color?
How should I modify the method below to give a darker color?
public static int getLighterColorByValue(int color, float factor) {
int red = (int) ((Color.red(color) * (1 - factor) / 255 + factor) * 255);
int green = (int) ((Color.green(color) * (1 - factor) / 255 + factor) * 255);
int blue = (int) ((Color.blue(color) * (1 - factor) / 255 + factor) * 255);
return Color.argb(Color.alpha(color), red, green, blue);
}
Upvotes: 1
Views: 188
Reputation: 140318
Considering only the red channel (since the logic for the others is identical):
int red = (int) ((Color.red(color) * (1 - factor) / 255 + factor) * 255);
You are calculating a weighted sum between the current red channel and 255 (full intensity). In simplified terms:
int newRed = (1 - factor) * oldRed + factor * 255;
So, instead of blending with full intensity, blend with zero intensity:
int newRed = (1 - factor) * oldRed + factor * 0;
or, more simply:
int newRed = (1 - factor) * oldRed;
So, using the format of your original code, just drop the + factor
:
int red = (int) ((Color.red(color) * (1 - factor) / 255) * 255);
But since 1 - factor
is a float
, dividing by 255 and multiplying by 255 gets you back to the same number again. So, more simply:
int red = (int) ((Color.red(color) * (1 - factor));
int green = (int) ((Color.green(color) * (1 - factor));
int blue = (int) ((Color.blue(color) * (1 - factor));
Sanity check:
factor == 0
, the new color is the same as the original colorfactor == 1
, (1 - factor) == 0
, so red == green == blue == 0
, i.e. the new color is black.Upvotes: 2