Created
June 15, 2016 19:48
-
-
Save ernest-ns/3fcf4c6fa6446b6bd67ebaf9c687d451 to your computer and use it in GitHub Desktop.
A color class to calculate the distance between 2 colors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyColor | |
attr_accessor :red, :blue, :green, :alpha | |
def initialize(args) | |
@red = args[:red] | |
@blue = args[:blue] | |
@green = args[:green] | |
@alpha = args[:alpha] || 1 | |
end | |
def distance(color) | |
red_diff = self.red - color.red | |
blue_diff = self.blue - color.blue | |
green_diff = self.green - color.green | |
alpha_product = self.alpha * color.alpha | |
(100) * Math.sqrt(((red_diff ** 2) + (blue_diff ** 2) + (green_diff ** 2)) * alpha_product/3 + (self.alpha - color.alpha) ** 2) | |
end | |
def distance_in_percentage(color) | |
(distance(color) * 100) / 25000 | |
end | |
end | |
c1 = MyColor.new({red: 233, green: 233, blue: 233}) | |
c2 = MyColor.new({red: 102, green: 102, blue: 102}) | |
c3 = MyColor.new({red: 212, green: 212, blue: 204}) | |
c4 = MyColor.new({red: 232, green: 232, blue: 232}) | |
c5 = MyColor.new({red: 0, green: 0, blue: 0}) | |
c4.distance_in_percentage(c2) | |
c1.distance_in_percentage(c4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment