Module: GD::GIS::ColorHelpers

Defined in:
lib/gd/gis/color_helpers.rb

Overview

Utility helpers for generating colors compatible with GD.

This module provides convenience methods for creating random RGB / RGBA colors and vivid colors suitable for map rendering and styling.

All methods return instances of Color.

Class Method Summary collapse

Class Method Details

.hsv_to_rgb(h, s, v) ⇒ Array<Integer>

Converts HSV color values to RGB.

Hue, saturation, and value are expected to be in the range 0.0–1.0.

Parameters:

  • h (Float)

    hue

  • s (Float)

    saturation

  • v (Float)

    value

Returns:

  • (Array<Integer>)

    RGB values in the range 0–255



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/gd/gis/color_helpers.rb', line 66

def self.hsv_to_rgb(h, s, v)
  i = (h * 6).floor
  f = (h * 6) - i
  p = v * (1 - s)
  q = v * (1 - (f * s))
  t = v * (1 - ((1 - f) * s))

  r, g, b =
    case i % 6
    when 0 then [v, t, p]
    when 1 then [q, v, p]
    when 2 then [p, v, t]
    when 3 then [p, q, v]
    when 4 then [t, p, v]
    when 5 then [v, p, q]
    end

  [(r * 255).to_i, (g * 255).to_i, (b * 255).to_i]
end

.random_rgb(min: 0, max: 255) ⇒ GD::Color

Generates a random RGB color.

Parameters:

  • min (Integer) (defaults to: 0)

    minimum channel value (0–255)

  • max (Integer) (defaults to: 255)

    maximum channel value (0–255)

Returns:

  • (GD::Color)


19
20
21
22
23
24
25
# File 'lib/gd/gis/color_helpers.rb', line 19

def self.random_rgb(min: 0, max: 255)
  GD::Color.rgb(
    rand(min..max),
    rand(min..max),
    rand(min..max)
  )
end

.random_rgba(min: 0, max: 255, alpha: nil) ⇒ GD::Color

Generates a random RGBA color.

Parameters:

  • min (Integer) (defaults to: 0)

    minimum channel value (0–255)

  • max (Integer) (defaults to: 255)

    maximum channel value (0–255)

  • alpha (Integer, nil) (defaults to: nil)

    alpha channel (0–255), random if nil

Returns:

  • (GD::Color)


33
34
35
36
37
38
39
40
# File 'lib/gd/gis/color_helpers.rb', line 33

def self.random_rgba(min: 0, max: 255, alpha: nil)
  GD::Color.rgba(
    rand(min..max),
    rand(min..max),
    rand(min..max),
    alpha || rand(50..255)
  )
end

.random_vividGD::Color

Generates a random vivid RGB color.

Vivid colors avoid low saturation and brightness values, making them suitable for distinguishing map features.

Returns:

  • (GD::Color)


48
49
50
51
52
53
54
55
# File 'lib/gd/gis/color_helpers.rb', line 48

def self.random_vivid
  h = rand
  s = rand(0.6..1.0)
  v = rand(0.7..1.0)

  r, g, b = hsv_to_rgb(h, s, v)
  GD::Color.rgb(r, g, b)
end