0
0
mirror of https://github.com/bec-project/bec_widgets.git synced 2025-07-13 19:21:50 +02:00

feat(utils): colors added convertor for rgba to hex

This commit is contained in:
2024-06-28 16:59:34 +02:00
parent 2e2d422910
commit 572f2fb811
2 changed files with 53 additions and 0 deletions

View File

@ -67,6 +67,44 @@ class Colors:
raise ValueError("Unsupported format. Please choose 'RGB', 'HEX', or 'QColor'.")
return colors
@staticmethod
def hex_to_rgba(hex_color: str, alpha=255) -> tuple:
"""
Convert HEX color to RGBA.
Args:
hex_color(str): HEX color string.
alpha(int): Alpha value (0-255). Default is 255 (opaque).
Returns:
tuple: RGBA color tuple (r, g, b, a).
"""
hex_color = hex_color.lstrip("#")
if len(hex_color) == 6:
r, g, b = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
elif len(hex_color) == 8:
r, g, b, a = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4, 6))
return (r, g, b, a)
else:
raise ValueError("HEX color must be 6 or 8 characters long.")
return (r, g, b, alpha)
@staticmethod
def rgba_to_hex(r: int, g: int, b: int, a: int = 255) -> str:
"""
Convert RGBA color to HEX.
Args:
r(int): Red value (0-255).
g(int): Green value (0-255).
b(int): Blue value (0-255).
a(int): Alpha value (0-255). Default is 255 (opaque).
Returns:
hec_color(str): HEX color string.
"""
return "#{:02X}{:02X}{:02X}{:02X}".format(r, g, b, a)
@staticmethod
def validate_color(color: tuple | str) -> tuple | str:
"""

View File

@ -58,3 +58,18 @@ def test_color_validation_RGBA():
assert "The color values must be between 0 and 255 in RGBA format (R,G,B,A)" in str(
excinfo.value
)
def test_hex_to_rgba():
assert Colors.hex_to_rgba("#FF5733") == (255, 87, 51, 255)
assert Colors.hex_to_rgba("#FF573380") == (255, 87, 51, 128)
assert Colors.hex_to_rgba("#FF5733", 128) == (255, 87, 51, 128)
with pytest.raises(ValueError):
Colors.hex_to_rgba("#FF573")
def test_rgba_to_hex():
assert Colors.rgba_to_hex(255, 87, 51, 255) == "#FF5733FF"
assert Colors.rgba_to_hex(255, 87, 51, 128) == "#FF573380"
assert Colors.rgba_to_hex(255, 87, 51) == "#FF5733FF"