Skip to content

Instantly share code, notes, and snippets.

@ryanmarshall
Last active May 12, 2017 04:18
Show Gist options
  • Save ryanmarshall/708675b60748be13dedd9791804d2875 to your computer and use it in GitHub Desktop.
Save ryanmarshall/708675b60748be13dedd9791804d2875 to your computer and use it in GitHub Desktop.
This helper class will find the closest hex color from an array of hex colors
# By: Ryan Marshall
#
# This helper class will find the closes hex color from an array of other hex colors
#
#
# colors = ["e00928","24519b","461b00", "dae12a", "ff9c3e",]
# color = "285fa2"
#
class HexColor
#
# Will match the closest hex color from an array of hex colors
#
def self.closest(color, colors)
difference = get_difference_array(color, colors)
index = difference.index( difference.min )
colors[index]
end
def self.get_difference_array(color, colors)
difference = []
colors.each do |c|
color_rgb = self.hex2rgb(color)
base_rgb = self.hex2rgb(c)
number =
( color_rgb[:red] - base_rgb[:red] ) *
( color_rgb[:red] - base_rgb[:red] ) +
( color_rgb[:green] - base_rgb[:green] ) *
( color_rgb[:green] - base_rgb[:green] ) +
( color_rgb[:blue] - base_rgb[:blue] ) *
( color_rgb[:blue] - base_rgb[:blue] )
difference << Math.sqrt(number)
end
difference
end
def self.hex2rgb(color)
r = Integer(color[0..1], 16)
g = Integer(color[2..3], 16)
b = Integer(color[4..5], 16)
{
red: r,
green: g,
blue: b,
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment