Sha256: 0fbae0571e6048f52aea8d8c2c2edd695de7011b6fac31b67c9405a77f1ac54a

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

module RainbowColors
  class Palette
    def self.random_color
      red   = rand(255)
      green = rand(255)
      blue  = rand(255)
      
      RainbowColors::Convertor.hex_from_rgb({ red: red, green: green, blue: blue })
    end
    
    def self.adjust_saturation(colors, variance)
      colors.map! do |c|
        hsl = RainbowColors::Convertor.hsl_from_hex c
        if variance > 0
          hsl[:saturation] = hsl[:saturation] + variance if hsl[:saturation] + variance <= 100
        else
          hsl[:saturation] = hsl[:saturation] + variance if hsl[:saturation] + variance >= 0
        end
        RainbowColors::Convertor.hex_from_hsl hsl
      end
    end
    
    def self.color_text(color_background)
      background_rgb = RainbowColors::Convertor.rgb_from_hex color_background
      
      # http://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx
      background_brightness = Math.sqrt(
        background_rgb[:red]   ** 2 * 0.241 +
        background_rgb[:green] ** 2 * 0.691 +
        background_rgb[:blue]  ** 2 * 0.068
      )
      
      background_brightness < 145 ? "#E6E6E6" : "#1A1A1A"
    end
    
    def self.color_accent(color_scheme, color_background)
      bg = RainbowColors::Convertor.rgb_from_hex color_background
      color_scheme.map! { |hex| RainbowColors::Convertor.rgb_from_hex(hex) }
      
      contrast_colors = []
      color_scheme.each do |c|
        delta_red   = [bg[:red], c[:red]].max     - [bg[:red], c[:red]].min
        delta_green = [bg[:green], c[:green]].max - [bg[:green], c[:green]].min
        delta_blue  = [bg[:blue], c[:blue]].max - [bg[:blue], c[:blue]].min
        color_difference = delta_red + delta_green + delta_blue
        
        contrast_colors << RainbowColors::Convertor.hex_from_rgb(c) if color_difference > 225
      end
      
      # Return random contrasting color color, if available
      contrast_colors.empty? ? self.color_text(color_background) : contrast_colors.sample
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rainbow_colors-0.3.2 lib/rainbow_colors/palette.rb