Skip to content

Commit

Permalink
fix(color): Add methods for Color to/from hex
Browse files Browse the repository at this point in the history
We probably should have done this a while ago but better late than never.
  • Loading branch information
chriswmackey committed Nov 15, 2024
1 parent 392193e commit 85d827b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
16 changes: 16 additions & 0 deletions ladybug/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
14 changes: 14 additions & 0 deletions tests/color_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 85d827b

Please sign in to comment.