Colour Shade

I wanted to be able to generate the shades of a particular colour.

This site has many themes with one main colour for the links and lines. But I wanted to be able to input the hex colour, that I had picked from the banner photo, and find a lighter shade for the menu section at the bottom.

Eric Meyer has written a Color Blender and I thought that I could do something similar using Ruby.

The program just takes the colour in hex (e.g. #ff0000 or even #f00), the shade number that you want and a number for the scale. Positive shade numbers make the colour lighter, negative numbers darker. Scale tops out at 100 and defaults to 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def colour_shade(colour, shade, scale=10)
  # default the scale to 100 if it is greater...
  scale = 100 if scale > 100

  # if the shade is out of the range of scale then reset shade to scale...
  if shade > 0
    shade = scale if shade > scale
  else
    shade = scale * -1 if shade < scale * -1
  end

  colour = "##{colour[1,1]*2}#{colour[2,1]*2}#{colour[3,1]*2}" if colour.length == 4

  # Convert the colours to decimal...
  colour_split = [(eval "0x#{colour[1,2]}"), (eval "0x#{colour[3,2]}"), (eval "0x#{colour[5,2]}")]

  # Calculate the shade...
  new_colour = "#"
  colour_split.each do |c|
    case
    when shade <  0: colour_shade = (c - ((c / scale) * shade.abs))
    when shade == 0: colour_shade = (c)
    when shade >  0: colour_shade = (c + (((255 - c) / scale) * shade))
    end
    new_colour << sprintf("0%x", colour_shade.to_i).slice(-2..-1).upcase
  end
  new_colour
end

Hover the mouse over the bars below to see what parameters were used to create the shades.

                     

                     

                     

Download the source code.

  • Posted on Sunday, 23 July 2006
  • Tagged with ruby, rails