Skip to content

Commit 32c4d62

Browse files
authored
Enhance color initialization with hex support (#1980)
* Enhance color initialization with hex support * add tests for examples given by OCP
1 parent 69e9514 commit 32c4d62

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

cadquery/occ_impl/assembly.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,9 @@ def __init__(self, *args, **kwargs):
226226
self.wrapped = Quantity_ColorRGBA()
227227
elif len(args) == 1:
228228
self.wrapped = Quantity_ColorRGBA()
229-
exists = Quantity_ColorRGBA.ColorFromName_s(args[0], self.wrapped)
229+
exists = Quantity_ColorRGBA.ColorFromName_s(
230+
args[0], self.wrapped
231+
) or Quantity_ColorRGBA.ColorFromHex_s(args[0], self.wrapped)
230232
if not exists:
231233
raise ValueError(f"Unknown color name: {args[0]}")
232234
elif len(args) == 3:

tests/test_assembly.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,36 @@ def test_color():
644644
assert c4.wrapped.GetRGB().Green() == pytest.approx(0.2)
645645
assert c4.wrapped.Alpha() == 0.5
646646

647+
# test for hex string for short sRGB color
648+
c5 = cq.Color("#FF0")
649+
assert c5.wrapped.GetRGB().Red() == 1
650+
assert c5.wrapped.GetRGB().Green() == 1
651+
assert c5.wrapped.GetRGB().Blue() == 0
652+
with pytest.raises(AttributeError):
653+
c5.wrapped.GetRGB().Alpha()
654+
655+
# test for hex string for short sRGBA color
656+
c6 = cq.Color("#FF0F")
657+
assert c6.wrapped.GetRGB().Red() == 1
658+
assert c6.wrapped.GetRGB().Green() == 1
659+
assert c6.wrapped.GetRGB().Blue() == 0
660+
assert c6.wrapped.Alpha() == 1.0
661+
662+
# test for hex string for RGB color
663+
c7 = cq.Color("#FFFF00")
664+
assert c7.wrapped.GetRGB().Red() == 1
665+
assert c7.wrapped.GetRGB().Green() == 1
666+
assert c7.wrapped.GetRGB().Blue() == 0
667+
with pytest.raises(AttributeError):
668+
c7.wrapped.GetRGB().Alpha()
669+
670+
# test for hex string for RGBA color
671+
c8 = cq.Color("#FFFF00FF")
672+
assert c8.wrapped.GetRGB().Red() == 1
673+
assert c8.wrapped.GetRGB().Green() == 1
674+
assert c8.wrapped.GetRGB().Blue() == 0
675+
assert c8.wrapped.Alpha() == 1.0
676+
647677
with pytest.raises(ValueError):
648678
cq.Color("?????")
649679

0 commit comments

Comments
 (0)