75 lines
2.7 KiB
Python
75 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from typing import Self, Sequence
|
|
from Utils.Check import Check
|
|
|
|
class Color:
|
|
|
|
def __init__(self:Self, inputs:str|int|Sequence[int]|Self, _type:str = "rgba") -> None:
|
|
|
|
self.red:int = 0x00
|
|
self.green:int = 0x00
|
|
self.blue:int = 0x00
|
|
self.alpha:int = 0xFF
|
|
|
|
if Check.is_string(inputs):
|
|
if inputs.startswith("#"):
|
|
inputs = inputs[1:]
|
|
if len(inputs) in (3, 4):
|
|
inputs = "".join([character * 2 for character in inputs])
|
|
if len(inputs) in (7, 9):
|
|
inputs = ("FF" + inputs[1:])[-8:]
|
|
self.alpha, self.red, self.green, self.blue = [int(inputs[i:i + 2], 16) for i in (0, 2, 4, 6)]
|
|
elif inputs.startswith("rgb"):
|
|
self.red, self.green, self.blue, self.alpha = ([(
|
|
int(item) if i < 3 else
|
|
int(float(item) * 0xFF)) for item, i in enumerate(inputs[inputs.find("(") + 1:inputs.find(")")].split(","))] + [0xFF])[:4]
|
|
elif Check.is_integer(inputs):
|
|
self.alpha = 0xFF - ((inputs >> 24) & 0xFF)
|
|
self.red = (inputs >> 16) & 0xFF
|
|
self.green = (inputs >> 8) & 0xFF
|
|
self.blue = inputs & 0xFF
|
|
elif Check.is_array(inputs):
|
|
if _type in ("rgb", "rgba") or True:
|
|
self.red, self.green, self.blue, self.alpha = (inputs + [0xFF] * 4)[:4]
|
|
elif isinstance(inputs, Color):
|
|
self.red = inputs.red
|
|
self.green = inputs.green
|
|
self.blue = inputs.blue
|
|
self.alpha = inputs.alpha
|
|
|
|
def to_rgba(self:Self) -> str:
|
|
return f"rgba({self.red}, {self.green}, {self.blue}, {self.alpha / 0xFF:.2f})"
|
|
|
|
def to_rgb(self:Self) -> str:
|
|
return f"rgb({self.red}, {self.green}, {self.blue})"
|
|
|
|
def to_hex(self:Self, with_alpha:bool = False) -> str:
|
|
return "#" + (f"{self.alpha:02X}" if with_alpha else "") + f"{self.red:02X}{self.green:02X}{self.blue:02X}"
|
|
|
|
@staticmethod
|
|
def mix(*colors:str|int|Sequence[int]|Self) -> Self:
|
|
if len(colors) == 0:
|
|
return Color(0)
|
|
|
|
base:Color = Color(colors[0])
|
|
color:str|int|Sequence[int]|Color
|
|
l:int = len(colors)
|
|
|
|
if l != 1:
|
|
for color in colors[1:]:
|
|
|
|
subcolor:Color = Color(color)
|
|
|
|
base.red += subcolor.red
|
|
base.green += subcolor.green
|
|
base.blue += subcolor.blue
|
|
base.alpha += subcolor.alpha
|
|
|
|
base.red //= l
|
|
base.green //= l
|
|
base.blue //= l
|
|
base.alpha //= l
|
|
|
|
return base |