Gradient Calculation in Ruby

For one of my projects I needed to calculate color values between two colors. This is what I came up with:

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
29
30
31
class Gradient
  attr_accessor :resolution, :R0, :G0, :B0, :R1, :G1, :B1

  def initialize(start, stop, resolution)
    @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
end

You can use it like this:

1
2
g = Gradient.new(0xe6ebf9, 0x33abe3, 100)
g.gradient(50)

And with the optional to_s(16) it will return a hex value, which can be used in the CSS code.

Comments

Copyright © 2013 - Tom Pesman - Powered by Octopress