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

hex_to_rgb(hex)

@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 two hex_to_rgb/1 implementations both returned white.
  • "#FF000080" returned {0, 0, 0} -- black for a valid 8-digit alpha hex, instead of dropping the alpha channel.
  • "#zzzzzz" raised MatchError from {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_color(from_color, to_color, progress)

@spec interpolate_color(String.t(), String.t(), float()) :: String.t()

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"

rgb_to_hex(arg)

@spec rgb_to_hex({number(), number(), number()}) :: String.t()

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"