Skip to content

Instantly share code, notes, and snippets.

@pintowar
Last active August 29, 2015 14:14
Show Gist options
  • Save pintowar/63980013c25f239f0ff6 to your computer and use it in GitHub Desktop.
Save pintowar/63980013c25f239f0ff6 to your computer and use it in GitHub Desktop.
gradient class that prints a color between blue and red with a step size of "resolution" (arg)
require 'chunky_png'
class Gradient
attr_accessor :resolution, :R0, :G0, :B0, :R1, :G1, :B1
def initialize(start = 0x0000ff, stop = 0xff0000, resolution = 100)
@resolution = Float(resolution)
@R0 = (start & 0xff0000) >> 16;
@G0 = (start & 0x00ff00) >> 8;
@B0 = (start & 0x0000ff) >> 0;
@R1 = (stop & 0xff0000) >> 16;
@G1 = (stop & 0x00ff00) >> 8;
@B1 = (stop & 0x0000ff) >> 0;
end
def gradient(step)
r = interpolate(@R0, @R1, step);
g = interpolate(@G0, @G1, step);
b = interpolate(@B0, @B1, step);
(((r << 8) | g) << 8) | b;
end
def interpolate(start, stop, step)
if (start < stop)
return (((stop - start) * (step / @resolution)) + start).round;
else
return (((start - stop) * (1 - (step / @resolution))) + stop).round;
end
end
def actual_color min, max, value
raise "value must be between min and max: #{min} <= #{value} <= #{max}" if value < min or value > max
final = (@resolution * (value - min)).to_f/(max - min)
gradient(final.round).to_s(16)
end
def hex_color min, max, value
'#'+actual_color(min, max, value).rjust(6, '0')
end
def map_color min, max, value
aux = actual_color(min, max, value).split('').each_cons(2).to_a
"bb" + ([0, 2, 4].map{|it| aux[it].join }.reverse.join)
end
end
grad = Gradient.new
colors = (1..100).map{ |c| grad.hex_color 1, 100, c }
# Creating an image from scratch, save as an interlaced PNG
png = ChunkyPNG::Image.new(100, 32, ChunkyPNG::Color::TRANSPARENT)
(0..99).each do |w|
(0..31).each do |h|
png[w,h] = ChunkyPNG::Color(colors[w])
end
end
png.save('/tmp/output.png', :interlace => true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment