Skip to content

Instantly share code, notes, and snippets.

@ajw725
Last active February 11, 2016 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajw725/28f85324a20321426178 to your computer and use it in GitHub Desktop.
Save ajw725/28f85324a20321426178 to your computer and use it in GitHub Desktop.
given a single intensity value and range parameters, return a hex string for color on red-green scale
# generate hex string for RGB color on a red-to-green scale. default scale is
# -1 to 1, with -1 = red, 0 = yellow, and 1 = green. options hash can be used to
# reverse the scale (-1 = green, 1 = red) or to provide numbers not centered on zero.
# For example:
# offset = 2, factor = 3: numbers range from -1 to +5
# offset = 3, factor = 1: numbers range from +2 to +4
#
# note that despite being a red-green scale, blue is added (with maximum
# contributions at -50% and +50% intensity) to avoid muddy/brown colors.
#
def red_green_scale( value, options = {} )
params = {
reverse: false, # makes -1 = green and 1 = red
factor: 1, # adjust scale, e.g. factor = 2 --> scale is -2 to 2
offset: 0, # adjust center of scale, e.g. offset = +2 --> scale is 1 to 3
}.merge!( options )
intensity = ( value - params[:offset] ) / params[:factor].to_f
# if bad params are given, it's possible for a value to be larger than the
# intended scale max/min (e.g. value of 1.5 on a -1 to 1 scale). if this
# happens, just assign the maximum intensity (-1 or 1)
if intensity.abs > params[:factor].abs
intensity = intensity <=> 0
end
if params[:reverse]
r = ( intensity >= 0 ? 255 : ( (1 - intensity.abs) * 255 ).to_i ).to_s( 16 )
g = ( intensity > 0 ? ( (1 - intensity.abs) * 255 ).to_i : 255 ).to_s( 16 )
else
r = ( intensity <= 0 ? 255 : ( (1 - intensity.abs) * 255 ).to_i ).to_s( 16 )
g = ( intensity < 0 ? ( (1 - intensity.abs) * 255 ).to_i : 255 ).to_s( 16 )
end
b = ( ( 127.5 - (0.5 - intensity.abs).abs * 255 ).abs.to_i ).to_s( 16 )
r = '0' + r if r.length == 1
g = '0' + g if g.length == 1
b = '0' + b if b.length == 1
return r + g + b
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment