diff --git a/ladybug/color.py b/ladybug/color.py index c1f8e27a..73f65a0d 100644 --- a/ladybug/color.py +++ b/ladybug/color.py @@ -35,6 +35,18 @@ def __init__(self, r=0, g=0, b=0, a=255): self.b = b self.a = a + @classmethod + def from_hex(cls, hex_string): + """Create a color from a hex code. + + Args: + hex_string: Text string of a hex code given as #rrggbb. + """ + value = hex_string.lower().lstrip('#') + lv = len(value) + rgb = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) + return cls(rgb[0], rgb[1], rgb[2]) + @classmethod def from_dict(cls, data): """Create a color from a dictionary. @@ -102,6 +114,10 @@ def duplicate(self): """Return a copy of the current color.""" return self.__copy__() + def to_hex(self): + """Get color as #rrggbb hex code.""" + return '#%02x%02x%02x' % (self.r, self.g, self.b) + def to_dict(self): """Get color as a dictionary.""" return { diff --git a/tests/color_test.py b/tests/color_test.py index 4fb6558f..8ae17b26 100644 --- a/tests/color_test.py +++ b/tests/color_test.py @@ -28,6 +28,20 @@ def test_init_color(): assert isinstance(c, int) +def test_color_to_from_hex(): + """Test the from_hex and to_hex methods.""" + hex_code = '#ffffff' + color = Color.from_hex(hex_code) + assert color.r == 255 + assert color.g == 255 + assert color.b == 255 + assert color.to_hex() == hex_code + + color = Color(255, 0, 100) + hex_code = color.to_hex() + assert color.from_hex(hex_code) == color + + def test_init_color_invalid(): """Test the initialization of invalid color objects.""" with pytest.raises(Exception):