Raxol. Utils. ColorConversion
(Raxol v2.8.0)
View Source
Utility functions for color conversions between hex and RGB formats.
Summary
Functions
Convert hex color to RGB tuple, falling back to black.
Interpolate between two colors.
Convert RGB tuple to hex color.
Functions
@spec hex_to_rgb(String.t()) :: {non_neg_integer(), non_neg_integer(), non_neg_integer()}
Convert hex color to RGB tuple, falling back to black.
Lenient by design: an unparseable string yields {0, 0, 0} rather than
raising. Raxol.Core.Renderer.Color.hex_to_rgb/1 is the strict counterpart
and raises ArgumentError.
Parsing itself is delegated to Raxol.Style.Colors.Formats.from_hex/1, the
one hex parser in the tree. The hand-rolled Integer.parse/2 version this
replaces was wrong in three ways, all fixed by delegating:
"#FFF"returned{0, 0, 0}-- black for a valid 3-digit shorthand, which this codebase's style maps do ship. The other twohex_to_rgb/1implementations both returned white."#FF000080"returned{0, 0, 0}-- black for a valid 8-digit alpha hex, instead of dropping the alpha channel."#zzzzzz"raisedMatchErrorfrom{r, ""} = :error, contradicting this function's own spec and the"invalid"doctest below.
Examples
iex> Raxol.Utils.ColorConversion.hex_to_rgb("#FF0000")
{255, 0, 0}
iex> Raxol.Utils.ColorConversion.hex_to_rgb("#0F0")
{0, 255, 0}
iex> Raxol.Utils.ColorConversion.hex_to_rgb("#FF000080")
{255, 0, 0}
iex> Raxol.Utils.ColorConversion.hex_to_rgb("invalid")
{0, 0, 0}
Interpolate between two colors.
Examples
iex> Raxol.Utils.ColorConversion.interpolate_color("#000000", "#FFFFFF", 0.5)
"#808080"
iex> Raxol.Utils.ColorConversion.interpolate_color("#000000", "#FFFFFF", 0.0)
"#000000"
iex> Raxol.Utils.ColorConversion.interpolate_color("#000000", "#FFFFFF", 1.0)
"#ffffff"
Convert RGB tuple to hex color.
Examples
iex> Raxol.Utils.ColorConversion.rgb_to_hex({255, 0, 0})
"#ff0000"
iex> Raxol.Utils.ColorConversion.rgb_to_hex({0, 255, 0})
"#00ff00"