Home > Enterprise >  How to calculate the best text color to contrast with background in rails
How to calculate the best text color to contrast with background in rails

Time:06-21

I need to calculate a color for the text, when a background is set and that color should be the best contrast possible. The color should not be between white or black, but some color that makes sense for contrast. is there any idea? tks

CodePudding user response:

Possible solution:

class InvalidFormat < StandardError; end

RGB_REGEXP = /\A#(..)(..)(..)\z/
VALID_FORMAT = /\A#[a-fA-F0-9]{6}\z/

def invert_color(hex, black_white = false)
  raise InvalidFormat unless hex =~ VALID_FORMAT

  red, green, blue = hex.match(RGB_REGEXP).captures.map(&:hex)

  return (red * 0.299   green * 0.587   blue * 0.114) > 186 ? '#000000' : '#FFFFFF' if black_white

  red = (255 - red).to_s(16)
  green = (255 - green).to_s(16)
  blue = (255 - blue).to_s(16)
  ['#', *[red, green, blue].map { |c| c.rjust(2, '0') }].join
end
invert_color('#de34fc')

# => #21cb03

invert_color('#ffffff')

# => #000000

invert_color('#000000')

# => #ffffff

invert_color('#de34fc', true)

# => #ffffff

Note: You need to pass color in format #XXXXXX or convert #XXX to #XXXXXX before passing. And also add prefix # to format XXXXXX

CodePudding user response:

You can try the Chroma-Gem.

def invert_color(color)
  rgba = Chroma.paint(color).rgb
  Chroma.paint("rgba(#{255 - rgba.r}, #{255 - rgba.g},#{255 - rgba.b}, 1.0").to_hex
end  

You should get the inverted color of the color in the parameter.

  • Related