Looks like GD2 doesn't support gradients out of the box. There are tons of PHP gradient implementations out there, so I borrowed ideas from them to create the following using Ruby's GD2 gem:
require 'rubygems'
require 'gd2'
# monkey patch in a gradient method
module GD2
class Canvas
def gradient(x1, y1, x2, y2, r1, g1, b1, r2, g2, b2)
height = y2 - y1
r_delta = (r1 - r2) / height
g_delta = (g1 - g2) / height
b_delta = (b1 - b2) / height
my_y = y1
my_r = r1
my_g = g1
my_b = b1
0.upto(height) do |i|
self.color = @image.palette.resolve Color[my_r, my_g, my_b]
self.rectangle(x1, my_y, x2, my_y + 1, true)
my_y += 1
my_r -= r_delta
my_g -= g_delta
my_b -= b_delta
end
end
end
end
if __FILE__ == $0
colors = [[0.77, 0.12, 0.23], [1.00, 0.49, 0.04], [0.67, 0.83, 0.45],
[0.41, 0.80, 0.94], [0.96, 0.55, 0.73], [1.00, 1.00, 1.00],
[1.00, 0.96, 0.41], [0.14, 0.35, 1.00], [0.58, 0.51, 0.79],
[0.78, 0.61, 0.43]]
i = 1
colors.each do |c|
image = GD2::Image.new(50, 50)
image.draw do |pen|
pen.gradient(0, 0, 100, 100, c[0], c[1], c[2], 0, 0, 0)
end
image.export("gradient-#{i}.png")
i += 1
end
end
Monkey patching for the win :-). The code as-is only creates vertical gradients, but hey,
it works and maybe it'll be useful to someone. Bonus points if anyone can spot the
significance of those 10 colors.