Module: LuminosityContrast

Defined in:
lib/luminosity_contrast.rb,
lib/luminosity_contrast/color.rb,
lib/luminosity_contrast/version.rb

Overview

Namespace for the gem. Contains methods to implement the Luminosity Contrast Ratio formula.

This module is not designed to be included in a class.

Defined Under Namespace

Classes: Color

Constant Summary collapse

VERSION =

gem version

"0.2.1"

Class Method Summary collapse

Class Method Details

.ratio(rgb1, rgb2) ⇒ Float

Calculate the Luminosity Contrast Ratio of two colors. This method is the gem's raison d'être.

Examples:

two RGB values as Arrays of three numbers

LuminosityContrast.ratio([0, 0, 0], [255.0, 255.0, 255.0])

two hex code strings (3 or 6 characters)

LuminosityContrast.ratio('000000', 'fff')

two LuminosityContrast::Color objects

LuminosityContrast.ratio(color1, color2)

Parameters:

  • rgb1

    either of two colors to compare

  • rgb2

    the other of two colors to compare

Returns:

  • (Float)

    the Luminosity Contrast Ratio between 1.0 and 21.0



22
23
24
25
26
# File 'lib/luminosity_contrast.rb', line 22

def ratio(rgb1, rgb2)
  c1, c2 = [rgb1, rgb2].map { |rgb| Color.new(rgb) }
  l1, l2 = [c1, c2].map(&:relative_luminance).sort
  (l2 + 0.05) / (l1 + 0.05)
end

.relative_luminance(r, g, b) ⇒ Float

Returns relative luminance of a color between 0.0 and 1.0.

Parameters:

  • r (Numeric)

    red component between 0.0 and 255.0

  • g (Numeric)

    green component between 0.0 and 255.0

  • b (Numeric)

    blue component between 0.0 and 255.0

Returns:

  • (Float)

    relative luminance of a color between 0.0 and 1.0



32
33
34
# File 'lib/luminosity_contrast.rb', line 32

def relative_luminance(r, g, b)
  (0.2126 * f(r)) + (0.7152 * f(g)) + (0.0722 * f(b))
end