Module: Vic::Color

Extended by:
Color
Included in:
Color
Defined in:
lib/vic/color.rb

Constant Summary collapse

SYSTEM_COLORS =

System colors (0-15)

[
  [0x00, 0x00, 0x00],
  [0x80, 0x00, 0x00],
  [0x00, 0x80, 0x00],
  [0x80, 0x80, 0x00],
  [0x00, 0x00, 0x80],
  [0x80, 0x00, 0x80],
  [0x00, 0x80, 0x80],
  [0xc0, 0xc0, 0xc0],
  [0x80, 0x80, 0x80],
  [0xff, 0x00, 0x00],
  [0x00, 0xff, 0x00],
  [0xff, 0xff, 0x00],
  [0x00, 0x00, 0xff],
  [0xff, 0x00, 0xff],
  [0x00, 0xff, 0xff],
  [0xff, 0xff, 0xff]
]
RGB_COLORS =

RGB colors (16 - 231)

[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff].repeated_permutation(3).to_a
GRAYSCALE_COLORS =

Grayscale colors (232 - 255)

(0x08..0xee).step(0x0a).to_a.map {|v| Array.new(3).fill(v) }
COLORS_256 =

All 256 colors of the rainbow. Organized from 0 to 255.

SYSTEM_COLORS + RGB_COLORS + GRAYSCALE_COLORS

Instance Method Summary collapse

Instance Method Details

#hex_to_256(hex) ⇒ FixNum

Takes a hexidecimal color and returns is closest 256 color match.

Credit goes to Micheal Elliot for the algorithm which was originally written in Python.

Parameters:

  • hex (String)

    the hexidecimal color

Returns:

  • (FixNum)

    the closest 256 color match

See Also:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/vic/color.rb', line 48

def hex_to_256(hex)
  parts = hex_to_rgb(hex)

  # If the hex is a member of the 256 colors club, we'll just return it's 256
  # color value. No sense in doing extra work, right?
  return COLORS_256.index(parts) if COLORS_256.include?(parts)

  increments = 0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff

  # For each part we need to check if it's between any two of the increments.
  # If it is we'll determine the closest match, change it's value, break,
  # and move on to the next part.
  parts.map! do |part|
    closest = nil
    for i in (0..(increments.length - 1))
      lower = increments[i]
      upper = increments[i + 1]
      next unless (lower <= part) && (part <= upper)
      distance_from_lower = (lower - part).abs
      distance_from_upper = (upper - part).abs
      closest = distance_from_lower < distance_from_upper ? lower : upper
      break
    end
    closest
  end

  # Return the index of the color
  COLORS_256.index(parts)
end

#hex_to_rgb(hex) ⇒ Array

Convert hexidecimal color to an Array of RGB values.

Parameters:

  • hex (String)

    the hexidecimal color

Returns:

  • (Array)

    the RGB color conversion



36
37
38
# File 'lib/vic/color.rb', line 36

def hex_to_rgb(hex)
  hex.match(/#?(..)(..)(..)/)[1..4].to_a.map {|v| v.to_i(16) }
end

#is_hexadecimal?(subject) ⇒ Match

Checks if the subjec is a valid hexidecimal color.

Parameters:

  • subject (String)

    the string in question

Returns:

  • (Match)

    Match



82
83
84
85
# File 'lib/vic/color.rb', line 82

def is_hexadecimal?(subject)
  return false unless subject.respond_to? :match
  subject.match(/#?[\da-f]{6}/i) ? true : false
end