Add colour.py with string based colour value
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
from functools import lru_cache
|
||||
import matplotlib.colors as colors
|
||||
|
||||
import numpy as np
|
||||
|
||||
class ColourValue(str):
|
||||
def __new__(cls, value, /, name=None) -> "ColourValue":
|
||||
hex_val = colors.to_hex(value, True)
|
||||
instance = super().__new__(cls, hex_val)
|
||||
|
||||
instance._name = name
|
||||
|
||||
return instance
|
||||
|
||||
def __repr__(self) -> str:
|
||||
if self.name:
|
||||
name = f"\"{self.name}\" "
|
||||
else:
|
||||
name = ""
|
||||
|
||||
return f"<{self.__class__.__name__}" \
|
||||
f" {name}{self} " \
|
||||
f"({self.rgba[0]:.2f}, {self.rgba[1]:.2f}, " \
|
||||
f"{self.rgba[2]:.2f}, {self.rgba[3]:.2f})>"
|
||||
|
||||
def alpha_adj(self, alpha):
|
||||
r, g, b, a = self.rgba
|
||||
return (r, g, b, alpha)
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def rgba(self) -> tuple[float, float, float, float]:
|
||||
return colors.to_rgba(self)
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def rgb(self) -> tuple[float, float, float]:
|
||||
return colors.to_rgb(self)
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def hsv(self) -> np.ndarray:
|
||||
return colors.rgb_to_hsv(self.rgb)
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def name(self) -> str:
|
||||
if hasattr(self, "_name") and self._name is not None:
|
||||
name = self._name
|
||||
else:
|
||||
name = ""
|
||||
|
||||
return name # ty:ignore[invalid-return-type]
|
||||
|
||||
@property
|
||||
def hex(self) -> str:
|
||||
return self
|
||||
|
||||
if __name__ == "__main__":
|
||||
foo = ColourValue((0,0.5,0.6), "Whoa a name!")
|
||||
print(foo)
|
||||
|
||||
exit()
|
||||
Reference in New Issue
Block a user