Files
NexusLauncher/ui/utilities/color_utils.py
2025-11-23 20:41:50 +08:00

88 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
颜色工具模块
负责颜色处理和转换
"""
def darken_color(hex_color: str, factor: float = 0.2) -> str:
"""使颜色变暗
Args:
hex_color: 十六进制颜色代码
factor: 变暗系数0-1 之间
Returns:
变暗后的十六进制颜色代码
"""
# 去除#前缀
hex_color = hex_color.lstrip('#')
# 转换为RGB
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
# 降低亮度
r = max(0, int(r * (1 - factor)))
g = max(0, int(g * (1 - factor)))
b = max(0, int(b * (1 - factor)))
# 转回十六进制
return f'#{r:02x}{g:02x}{b:02x}'
def lighten_color(hex_color: str, factor: float = 0.2) -> str:
"""使颜色变亮
Args:
hex_color: 十六进制颜色代码
factor: 变亮系数0-1 之间
Returns:
变亮后的十六进制颜色代码
"""
# 去除#前缀
hex_color = hex_color.lstrip('#')
# 转换为RGB
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
# 提高亮度
r = min(255, int(r + (255 - r) * factor))
g = min(255, int(g + (255 - g) * factor))
b = min(255, int(b + (255 - b) * factor))
# 转回十六进制
return f'#{r:02x}{g:02x}{b:02x}'
def hex_to_rgb(hex_color: str) -> tuple:
"""将十六进制颜色转换为RGB元组
Args:
hex_color: 十六进制颜色代码
Returns:
RGB颜色元组 (r, g, b)
"""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def rgb_to_hex(r: int, g: int, b: int) -> str:
"""将RGB颜色转换为十六进制
Args:
r: 红色分量 (0-255)
g: 绿色分量 (0-255)
b: 蓝色分量 (0-255)
Returns:
十六进制颜色代码
"""
return f'#{r:02x}{g:02x}{b:02x}'