DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Get The Inverse Of A Hex Color In Ruby

08.17.2005
| 4955 views |
  • submit to reddit
        This method will return the inverse of a hex color, which is useful if you want to make sure that your text will show up on a colored background.

def invert_color(color)
  color.gsub!(/^#/, '')
  sprintf("%X", color.hex ^ 0xFFFFFF)
end

Example:

invert_color('#c0c0c0') #=> "3F3F3F"

Limitations:

Doesn't handle named colors or 3 digit colors (i.e. #FFF == #FFFFFF)

    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

def invert_color(color) color.gsub!(/^#/, '') color += color if color.length == 3 sprintf("%X", color.hex ^ 0xFFFFFF) end that should take care of the 3 letter hex cases...