Gradient background images with ruby and chunky_png

I recently decided that I wanted to make a series of solid colour backgrounds for my laptop. The reasons are nominally grounded in productivity1, but given that the whole exercise sent me down a rabbit-hole of writing code and then this blog post, let’s just call it a little experiment to see what we can do, shall we?

Step 1: Making a solid colour PNG

Our first step will be to create a solid colour PNG of the right size. I’m going to use the ruby gem ChunkyPNG to do all the heavy lifting. Let’s get started!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env ruby

require 'chunky_png'

HEIGHT = 800
WIDTH = 800

HUE = rand(360)
puts "Making a background with hue #{HUE}"
LUMINESCENCE = 0.5

image = ChunkyPNG::Image.new(WIDTH, HEIGHT)

1.upto(HEIGHT) do |y|
  1.upto(WIDTH) do |x|
    image[x - 1, y - 1] = ChunkyPNG::Color.from_hsl(HUE, 1, LUMINESCENCE)
  end
end

image.save("background.png")

This script:

  1. Sets the height and width of our image
  2. Picks an appropriate hue (randomly set in this instance) and luminence
  3. Generates the image and sets every pixel to the specified colour
  4. Saves it to background.png

Here’s an example, generated using the script above:

Wow, look at all that colour

Step 2: Let’s make it prettier

OK so we can make solid colour backgrounds automatically, big deal. We can do that in MS paint! What if we want to make them look a bit cooler? And what’s cooler than an automatically generated linear gradient?

This is going to take a few steps, however, and we’re going to have to go back to high school trigonometry. Ready for some maths? Let’s get stuck in.

So: if we apply a linear gradient with an angle θ, all points situated on a line at 90° to this gradient will have the same colour. We can show this visually:

All points along the thin lines will have the same colour - they’re all at 90° to the gradient vector.

So obviously when we’re just looking at this diagram, we can trace a given point back onto that gradient line. How do we do that mathematically? We use a geometric technique called projection to see how far down the gradient line a given point falls. We can do this by imagining a given point p(x,y) as a point on a right-angled triangle, as follows:

I’ll try not to introduce any more Greek letters, I swear.

OK, so what’s that distance d, the projection of the point onto the gradient? Well, we know from trigonometry that:

cosɸ = d / h
d = hcosɸ

OK, but what does that mean? After all, right now all we know is the angle of our gradient (we get to decide this), and the x and y coordinates of our point P (we’re going to iterate over all points, so this is going to change as we go).

So how do we calculate any of these values?

Let’s start with h. This is the distance between the top-left pixel and our point P. Pythagorus has a theorem for this:

h = √(x² + y²)

Easy! Now, what about ɸ? This is the angle of the right-angle triangle, and it’s just the difference between our gradient angle θ and, well, whatever angle our point P makes with the top of the screen. Trigonometry to the rescue:

ɸ = |θ - tan⁻¹(y/x)|

(We mark the whole thing as absolute as we always want to have a positive value here.)

So that’s the maths. What does it look like in code? Here’s a ruby function that, given a point with a given x and y, and a given gradient, calculates the projection of the point on the gradient line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Calculate a gradient projection, given a point (x,y) and a gradient
# angle of `gradient` in radians.
def gradient_projection(x, y, gradient)

  # Calculate angles
  point_angle = Math::atan(y / x)
  triangle_angle =  (gradient - point_angle).abs

  # Calculate distance from (0, 0) to (x, y)
  point_distance = Math::sqrt(x**2 + y**2)

  # Calculate projection
  return point_distance * Math::cos(triangle_angle)
end

So how do we use this in constructing a gradient? There’s all kinds of ways you can do this - in the example below I’m going to transition between two luminescence values - one at the top left and one at the bottom right:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env ruby 

require 'chunky_png'

# Constants
HEIGHT = 800
WIDTH = 800

# We use this for interpolating luminescence
DIAGONAL = Math::sqrt(HEIGHT**2 + WIDTH**2)

HUE = rand(360)

LUMINESCENCE_START = 0.5
LUMINESCENCE_END = 0.3

# We need to convert this from degrees to radians
GRADIENT_ANGLE_DEGREES = 45
GRADIENT_ANGLE = GRADIENT_ANGLE_DEGREES * Math::PI / 180

# Calculate a gradient projection, given a point (x,y) and a gradient
# angle of `gradient` in radians.
def gradient_projection(x, y, gradient)

  # Calculate angles
  point_angle = Math::atan(y / x)
  triangle_angle =  (gradient - point_angle).abs

  # Calculate distance from (0, 0) to (x, y)
  point_distance = Math::sqrt(x**2 + y**2)

  # Calculate projection
  return point_distance * Math::cos(triangle_angle)
end

image = ChunkyPNG::Image.new(WIDTH, HEIGHT)

1.upto(HEIGHT) do |y|
  1.upto(WIDTH) do |x|

    # Calculate projection as a fraction of DIAGONAL
    proj = gradient_projection(x, y, GRADIENT_ANGLE)
    proj_fxn = proj / DIAGONAL

    lum = LUMINESCENCE_START + (LUMINESCENCE_END - LUMINESCENCE_START) * proj_fxn

    image[x - 1, y - 1] = ChunkyPNG::Color.from_hsl(HUE, 1, lum)
  end
end

image.save("background2.png")

Looks good? It works (almost!) perfectly!

Except for one little flaw…

Astute readers will notice that something weird is going on here - the bottom-left side of the image is fine, but the top-right isn’t doing what it should. If you’re feeling like a challenge, see if you can identify the issue before reading on!

OK, if you just want to know what the issue is - it’s in how ruby treats integer division (namely, it gets rid of any fractions). This means that our issue exists in the following line:

1
point_angle = Math::atan(y / x)

If y < x, y / x will always equal zero. We can fix this by converting y to a floating point decimal first:

1
point_angle = Math::atan(y.to_f / x)

Much better.

In the end, I just stepped through all 360 degrees of hue at 10 degrees per step to create 36 backgrounds to cycle through, but you may want to pick out your favourite colours, or play around with the logic.

Bonus round: radial gradients!

We’re not just limited to linear gradients, especially not given we’re generating this pixel-by-pixel. Let’s have a go at generating a radial gradient centred on the top-left, rather than our linear gradient.

This is actually easier than the linear gradient - all we need to do is calculate the distance from top left and use that to calculate luminescence:

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
32
33
34
#!/usr/bin/env ruby 

require 'chunky_png'

# Constants
HEIGHT = 800
WIDTH = 800

HUE = rand(360)

LUMINESCENCE_START = 0.5
LUMINESCENCE_END = 0.3

def dist(x, y)
  Math::sqrt(x**2 + y**2)
end

DIAGONAL = dist(WIDTH, HEIGHT)

image = ChunkyPNG::Image.new(WIDTH, HEIGHT)

1.upto(HEIGHT) do |y|
  1.upto(WIDTH) do |x|

    # Calculate projection as a fraction of DIAGONAL
    dist_fxn = dist(x, y).to_f / DIAGONAL

    lum = LUMINESCENCE_START + (LUMINESCENCE_END - LUMINESCENCE_START) * dist_fxn

    image[x - 1, y - 1] = ChunkyPNG::Color.from_hsl(HUE, 1, lum)
  end
end

image.save("background4.png")

Easy peasy.

In fact, it’s so easy that we could even specify an origin point which isn’t the top left…

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
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env ruby 

require 'chunky_png'

# Constants
HEIGHT = 800
WIDTH = 800

HUE = rand(360)

LUMINESCENCE_START = 0.5
LUMINESCENCE_END = 0

ORIGIN_X = 400
ORIGIN_Y = 200

def dist(x, y)
  Math::sqrt(x**2 + y**2)
end

def dist_from_origin(x, y)
  dist(x - ORIGIN_X, y - ORIGIN_Y)
end

DIAGONAL = dist(WIDTH, HEIGHT)

image = ChunkyPNG::Image.new(WIDTH, HEIGHT)

1.upto(HEIGHT) do |y|
  1.upto(WIDTH) do |x|

    # Calculate projection as a fraction of DIAGONAL
    dist_fxn = dist_from_origin(x, y).to_f / DIAGONAL

    lum = LUMINESCENCE_START + (LUMINESCENCE_END - LUMINESCENCE_START) * dist_fxn

    image[x - 1, y - 1] = ChunkyPNG::Color.from_hsl(HUE, 1, lum)
  end
end

image.save("background5.png")

Lemon squeezy

So there you have it. We’ve not only generated a random-colour background, we’ve applied two different gradients to those colours. And I guess I can get back to doing all the things I was supposed to be doing before this distraction came along.


  1. Previously I’d been using Unsplash’s app for OS X to select a random image from their site, but I was wondering if having busy backgrounds actively breaks me out of focus during the day. The obvious solution was to build a series of solid-colour wallpapers - solid colour so there was nothing distracting, and a series so I didn’t have the same colour all the time. 

Comments

Leave a comment

Sorry, you need to enable javascript for commenting. That’s one of the drawbacks of having a static site blog I guess.