69 lines
2.8 KiB
Python
69 lines
2.8 KiB
Python
def adjust_brightness(rgb_color, brightness):
|
|
r, g, b = rgb_color
|
|
# Convert 0-255 brightness to a scale of 0-1
|
|
scale_factor = brightness / 255.0
|
|
|
|
adjusted_r = int(r * scale_factor)
|
|
adjusted_g = int(g * scale_factor)
|
|
adjusted_b = int(b * scale_factor)
|
|
|
|
# Ensure values are within 0-255
|
|
adjusted_r = max(0, min(255, adjusted_r))
|
|
adjusted_g = max(0, min(255, adjusted_g))
|
|
adjusted_b = max(0, min(255, adjusted_b))
|
|
|
|
return (adjusted_r, adjusted_g, adjusted_b)
|
|
|
|
|
|
def hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
|
|
"""Converts a hex color string (e.g., "#RRGGBB") to an RGB tuple."""
|
|
hex_color = hex_color.lstrip('#')
|
|
return int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
|
|
|
|
def rgb_to_hex(r: int, g: int, b: int) -> str:
|
|
"""Converts an RGB tuple to a hex color string (e.g., "#RRGGBB")."""
|
|
return f"#{r:02x}{g:02x}{b:02x}"
|
|
|
|
def get_contrast_text_color(background_hex_color: str) -> str:
|
|
"""
|
|
Determines whether black or white text is more readable on a given background color.
|
|
Uses the WCAG 2.0 contrast recommendations (Luminosity calculation).
|
|
"""
|
|
r, g, b = hex_to_rgb(background_hex_color)
|
|
|
|
# Convert RGB to sRGB (0-1 range)
|
|
# The linear RGB values are normalized by dividing by 255
|
|
r_linear = r / 255.0
|
|
g_linear = g / 255.0
|
|
b_linear = b / 255.0
|
|
|
|
# Apply the sRGB to linear conversion for gamma correction
|
|
# This is a simplified approximation for readability, a more accurate one involves if/else for values <= 0.03928
|
|
# For a general "light vs dark" determination, this simplified approach is often sufficient.
|
|
# The formula used here is often simplified as (R*0.299 + G*0.587 + B*0.114) for quick luminance.
|
|
# A more precise relative luminance (L) calculation:
|
|
def srgb_to_linear(c):
|
|
if c <= 0.03928:
|
|
return c / 12.92
|
|
else:
|
|
return ((c + 0.055) / 1.055) ** 2.4
|
|
|
|
L = (0.2126 * srgb_to_linear(r_linear) +
|
|
0.7152 * srgb_to_linear(g_linear) +
|
|
0.0722 * srgb_to_linear(b_linear))
|
|
|
|
# For general UI elements, a luminance threshold around 0.179 (sqrt(0.032)) is often used
|
|
# or simply checking if (R*0.299 + G*0.587 + B*0.114) is > 186 for light background / dark text
|
|
# A common rule of thumb for perceived brightness (closer to the one used in many UIs):
|
|
# (R*299 + G*587 + B*114) / 1000
|
|
# Let's use a simpler luminance check based on the first example's intention:
|
|
# If the perceived brightness is above a certain threshold, use black text. Otherwise, use white.
|
|
|
|
# A simpler luminance check often used for text contrast:
|
|
luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
|
|
|
|
if luminance > 0.5: # Adjust this threshold as needed for perceived contrast
|
|
return "black"
|
|
else:
|
|
return "white"
|