diff --git a/examples/bars.py b/examples/bars.py index 7a007891..005e8c47 100644 --- a/examples/bars.py +++ b/examples/bars.py @@ -6,6 +6,7 @@ Use Bar to renderer a sort-of cirlce. import math from rich.bar import Bar +from rich.color import Color from rich import print @@ -14,5 +15,6 @@ SIZE = 40 for row in range(SIZE): y = (row / SIZE) * 2 - 1 x = math.sqrt(1 - y * y) - bar = Bar(1, width=SIZE * 2, begin=1 - x, end=x, color="red") + color = Color.from_rgb((y + 1) * 127, 0, 0) + bar = Bar(1, width=SIZE * 2, begin=1 - x, end=x, color=color) print(bar) diff --git a/rich/color.py b/rich/color.py index 402e7979..bba7dd80 100644 --- a/rich/color.py +++ b/rich/color.py @@ -339,6 +339,21 @@ class Color(NamedTuple): """ return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet) + @classmethod + def from_rgb(cls, red: float, green: float, blue: float) -> "Color": + """Create a truecolor from three color components in the range(0->255). + + Args: + red (float): Red component. + green (float): Green component. + blue (float): Blue component. + + Returns: + Color: A new color object. + """ + triplet = ColorTriplet(int(red), int(green), int(blue)) + return cls.from_triplet(triplet) + @classmethod def default(cls) -> "Color": """Get a Color instance representing the default color. diff --git a/tests/test_color.py b/tests/test_color.py index c3607b24..d5ecffd5 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -67,6 +67,12 @@ def test_from_triplet() -> None: ) +def test_from_rgb() -> None: + assert Color.from_rgb(0x10, 0x20, 0x30) == Color( + "#102030", ColorType.TRUECOLOR, None, ColorTriplet(0x10, 0x20, 0x30) + ) + + def test_default() -> None: assert Color.default() == Color("default", ColorType.DEFAULT, None, None)