Programmatically darken a Hex colour

以编程方式使十六进制颜色变暗的最简单方法是什么?


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

A function implemented in javascript:

// credits: richard maloney 2006
function getTintedColor(color, v) {
    if (color.length >6) { color= color.substring(1,color.length)}
    var rgb = parseInt(color, 16); 
    var r = Math.abs(((rgb >> 16) & 0xFF)+v); if (r>255) r=r-(r-255);
    var g = Math.abs(((rgb >> 8) & 0xFF)+v); if (g>255) g=g-(g-255);
    var b = Math.abs((rgb & 0xFF)+v); if (b>255) b=b-(b-255);
    r = Number(r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r).toString(16); 
    if (r.length == 1) r = '0' + r;
    g = Number(g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g).toString(16); 
    if (g.length == 1) g = '0' + g;
    b = Number(b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b).toString(16); 
    if (b.length == 1) b = '0' + b;
    return "#" + r + g + b;
} 

Example:

> getTintedColor("ABCEDEF", 10)
> #c6f7f9
链接地址: http://www.djcxy.com/p/87406.html

上一篇: 如何在Android中将颜色整数转换为十六进制字符串?

下一篇: 以编程方式使十六进制颜色变暗