What's the easiest way to programmatically darken a hex colour?
A hex colour such as #FCFCFC consists of three pairs representing RGB. The second part of each pair can be reduced to darken any colour without altering the colour considerably. Reducing the first part of each pair by a small amount will also darken the colour, but you will start to affect the colour more (eg.
Using an alpha value to update a color's transparency will change the hex code format from #RRGGBB to #RRGGBBAA (where alpha is A ). The first six values (the red, green, and blue ones) remain the same. The AA value in #RRGGBBAA can range from the lowest value possible ( 00 ) to the highest value possible ( FF ).
For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade. For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.
If you're not bothered about too much control, and just want a generally darker version of a colour, then:
col = (col & 0xfefefe) >> 1;
Is a nice quick way to halve a colour value (assuming it's packed as a byte per channel, obviously).
In the same way brighter would be:
col = (col & 0x7f7f7f) << 1;
Convert hex color into integer RBG components:
#FF6600 = rbg(255, 102, 0)
If you want to make it darker by 5%, then simply reduce all integer values by 5%:
255 - 5% = 242 102 - 5% = 96 0 - 5% = 0 = rbg(242, 96, 0)
Convert back to hex color
= #F26000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With