Shpigford
Shpigford

Reputation: 25338

Generate hex numbers based on percentage

I'm looking for a way to generate a gradual hexadecimal color based on a percentage with Ruby.

0% = #6da94a
50% = #decc30
100% = #ce2d4a

Then programmatically generate the hexadecimal values in between those.

So I might have something like percent_to_hex(10) and that would spit out whatever hexadecimal value is 10% along the gradual gradient between 0% (green) and 50% (yellow).

Upvotes: 1

Views: 551

Answers (2)

vmanolov
vmanolov

Reputation: 84

Actually there is a small mistake in tralston's answer.

(x + percent * 100 * (y - x)).round

should be changed to:

(x + percent / 100.0 * (y - x)).round

Also i.to_s(16) would be a problem if you have 0 (255), as you can get a result like "ff0ff". I would recommend using "%02x" % i instead.

Here is the complete example:

def percent_to_hex(percent, start, stop)
  colors = [start,stop].map do |c|
    c.scan(/../).map { |s| s.to_i(16) }
  end

  colors_int = colors.transpose.map do |x,y|
    (x + percent / 100.0 * (y - x)).round
  end

  colors_int.map { |i| "%02x" % i }.join("")
end

Upvotes: 2

tralston
tralston

Reputation: 3035

Not a very polished method, but here's a good start:

# Example input: percent_to_hex(25, "abcdef", "ffffff") => "c0daf3"
def percent_to_hex(percent, start, stop)
  colors = [start,stop].map do |c|
    c.scan(/../).map { |s| s.to_i(16) }
  end

  colors_int = colors.transpose.map do |x,y|
    (x + percent * 100 * (y - x)).round
  end

  colors_int.map { |i| i.to_s(16) }.join("")
end

Of course if you could customize it further to add or remove the leading "#" of the hex color code, etc.

Upvotes: 0

Related Questions