Created
June 11, 2023 13:44
-
-
Save eli-kha/4b958a888b64230cc2b6eb9351f23750 to your computer and use it in GitHub Desktop.
A demo of automatic text color selection based on the background color for NiceGUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from random import choices | |
from typing import Tuple | |
from nicegui import ui | |
def get_rgb(hex_color: str) -> Tuple[int, int, int]: | |
match = re.match(r'^#?.{0,2}([a-zA-Z0-9]{6})$', hex_color) | |
if match: | |
hex_color = match.group(1) | |
else: | |
raise ValueError('not a valid hex color') | |
r, g, b = tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4)) | |
return r, g, b | |
def get_brightness(rgb: Tuple[int, int, int]) -> int: | |
""" http://www.w3.org/TR/AERT#color-contrast """ | |
brightness = round(((int(rgb[0]) * 299) + | |
(int(rgb[1]) * 587) + | |
(int(rgb[2]) * 114)) / 1000) | |
return brightness | |
def get_text_color(brightness: int) -> str: | |
return 'black' if brightness > 125 else 'white' | |
but = ui.button('A text', color='#000000') | |
label = ui.label('The color') | |
def click_handle(): | |
random_bg_color = '#'+''.join(choices('0123456789abcdef', k=6)) | |
label.text = random_bg_color | |
but.style(f'background-color:{random_bg_color}') | |
but.style(f'color:{get_text_color(get_brightness(get_rgb(random_bg_color)))}') | |
but.on('click', click_handle) | |
ui.run(native=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment