开发者

Android changing a color's brightness

开发者 https://www.devze.com 2023-02-02 18:43 出处:网络
I want to change开发者_运维技巧 the brightness of any given color (Note: I am not talking about screen brightness), I have looked at the Color class, it has a few methods for conversions between RGB a

I want to change开发者_运维技巧 the brightness of any given color (Note: I am not talking about screen brightness), I have looked at the Color class, it has a few methods for conversions between RGB and HSV, I'm a newbie in this area. To start with, how do I change the brightness of red, if its value is spefied in RGB (#FF0000)?


The easiest way would be to convert the color to HSL (not HSV! they are different - see http://en.wikipedia.org/wiki/HSL_and_HSV) and change the L component - increase to make it brighter, decrease to make it darker.


Considering that you are talking about brightness (color enhance) and not luminance (white amount), your model is the HSV (aka HSB) and not HSL.

On fast briefing, if you enhance the V channel on HSV over, lets say... some blue, you have a "more blue" color. If you enhance the L channel on HSL model you have a more "clear and washed" blue.

The android.graphics.Color class have built-in support to HSV model. Use Color.colorToHSV() and Color.HSVToColor() to edit the brightness value (or hue, or saturation, if you like).

On HSV model, H (hue) define the base color, S (saturation) control the amount of gray and V controls the brightness. So, if you enhance V and decrease S at same time, you gets more luminance, in pratice.


For starters, you need to remember two things -

  1. To reduce brightness, you can change red from #FF0000 to #AA0000 or #880000 - basically reduce the Red component.
  2. You can also try reducing opacity - often you'll realize that it works better than just reducing brightness.


You can use Color.colorToHSV to convert the color to HSV, then change the brightness of the HSV color, then use Color.HSVToColor to convert it back to a color int. For example, the following code sets the brightness to 0.5:

@ColorInt int originalColor = /*your original color*/;
float[] hsv = new float[3];    //Create an array to pass to the colorToHSV function
Color.colorToHSV(originalColor, hsv);    //Put the HSV components in the array created above
hsv[2] = 0.5f;    //Whatever brightness you want to set. 0 is black, 1 is the pure color.
@ColorInt int newColor = Color.HSVToColor(hsv);    //Convert it back to a ColorInt
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号