Skip to content

Instantly share code, notes, and snippets.

@kaugm
Created September 30, 2021 17:23
Show Gist options
  • Save kaugm/fd61f392c8b41420ac28b107f5973b54 to your computer and use it in GitHub Desktop.
Save kaugm/fd61f392c8b41420ac28b107f5973b54 to your computer and use it in GitHub Desktop.
Create contrasting color for foreground text and elements
import re
def contrast(basecolor, format='HEX'):
'''
Create a contrasting color for foreground text and elements
Depending on the color [argument], return either black or white hex code
Useful for automatically coloring text which overlays a background
Output formats: HEX (hexidecimal) and RGB (as tuple)
'''
# Validate input
regex = '^#?([a-f0-9]{6}|[a-f0-9]{3})$'
if len(re.findall(regex, basecolor)) != 1:
raise ValueError('Please enter a proper hex color code: #ffffff or #fff')
else:
hexcode = basecolor[1:]
# Split into R,G,B into individual values
rgb_values = [hexcode[i:i + int(len(hexcode) / 3)] for i in range(0, len(hexcode), int(len(hexcode) / 3))]
# Check for single values and double them: #fff is shorthand for #ffffff
rgb_values = [i*2 if len(i) == 1 else i for i in rgb_values]
#Convert to decimal
red = int(rgb_values[0], 16)
green = int(rgb_values[1], 16)
blue = int(rgb_values[2], 16)
# Calculate luminance
luminance = float((0.299 * red + 0.587 * green + 0.114 * blue)/255)
# Calculate d (darkness) value
if luminance > 0.5:
d = 0
else:
d = 255
# Convert darkness value to hex value and create hex color code or RGB tuple
if format == 'HEX':
return f'#{d:X}{d:X}{d:X}'
else: # format = RGB
return (d, d, d)
@kaugm
Copy link
Author

kaugm commented Apr 21, 2022

Use Case:
Solid desktop background (wallpaper) changes from light to dark, or vice versa, on a regular basis. This can cause issues reading text displayed on Desktop (conky, rainmeter, etc.). This script will create a contrasting color hex code to standout from that wallpaper for readability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment