|
| 1 | +defmodule Matplotex.Colorscheme.Rgb do |
| 2 | + @moduledoc false |
| 3 | +alias Matplotex.Colorscheme.Colormap |
| 4 | + defstruct [ |
| 5 | + red: 0.0, # 0-255 |
| 6 | + green: 0.0, # 0-255 |
| 7 | + blue: 0.0, # 0-255 |
| 8 | + alpha: 1.0 # 0-1 |
| 9 | + ] |
| 10 | + |
| 11 | + def rgb(red, green, blue, alpha\\1.0) |
| 12 | + def rgb({red, :percent}, {green, :percent}, {blue, :percent}, alpha) do |
| 13 | + rgb(red * 255, green * 255, blue * 255, alpha) |
| 14 | + end |
| 15 | + def rgb(red, green, blue, alpha) do |
| 16 | + %__MODULE__{ |
| 17 | + red: cast(red, :red), |
| 18 | + green: cast(green, :green), |
| 19 | + blue: cast(blue, :blue), |
| 20 | + alpha: cast(alpha, :alpha) |
| 21 | + } |
| 22 | + end |
| 23 | + |
| 24 | + def to_string(struct, type\\nil) |
| 25 | + |
| 26 | + def to_string(struct, :nil) do |
| 27 | + type = case struct.alpha do |
| 28 | + 1.0 -> :hex |
| 29 | + _ -> :rgba |
| 30 | + end |
| 31 | + to_string(struct, type) |
| 32 | + end |
| 33 | + |
| 34 | + def to_string(%__MODULE__{red: r, green: g, blue: b, alpha: alpha}, :rgba) do |
| 35 | + "rgba(#{round(r)}, #{round(g)}, #{round(b)}, #{alpha})" |
| 36 | + end |
| 37 | + def to_string(%__MODULE__{red: r, green: g, blue: b, alpha: 1.0}, :hex) do |
| 38 | + "#" <> to_hex(r) <> to_hex(g) <> to_hex(b) |
| 39 | + end |
| 40 | + |
| 41 | + def cast(value, field) when field in [:red, :green, :blue] do |
| 42 | + value/1 |
| 43 | + |> min(255.0) |
| 44 | + |> max(0.0) |
| 45 | + end |
| 46 | + def cast(value, :alpha) do |
| 47 | + value/1 |
| 48 | + |> min(1.0) |
| 49 | + |> max(0.0) |
| 50 | + end |
| 51 | + |
| 52 | + defp to_hex(value) when is_float(value), do: |
| 53 | + to_hex(round(value)) |
| 54 | + defp to_hex(value) when value < 16, do: |
| 55 | + "0" <> Integer.to_string(value, 16) |
| 56 | + defp to_hex(value) when is_integer(value), do: |
| 57 | + Integer.to_string(value, 16) |
| 58 | + |
| 59 | + def from_hex!(input) do |
| 60 | + {:ok, color} = from_hex(input) |
| 61 | + color |
| 62 | + end |
| 63 | + |
| 64 | + def from_cmap!(%Colormap{color: color} = cmap) do |
| 65 | + %Colormap{cmap | color: from_hex!(color) } |
| 66 | + end |
| 67 | + |
| 68 | + def from_hex("#" <> <<r :: binary-size(2), g :: binary-size(2), b :: binary-size(2)>>) do |
| 69 | + {:ok, rgb(parse_hex(r), parse_hex(g), parse_hex(b))} |
| 70 | + end |
| 71 | + def from_hex("#" <> <<r :: binary-size(1), g :: binary-size(1), b :: binary-size(1)>>) do |
| 72 | + {:ok, rgb(parse_hex(r <> r), parse_hex(g <> g), parse_hex(b <> b))} |
| 73 | + end |
| 74 | + |
| 75 | + defp parse_hex(s), do: String.to_integer(s, 16) |
| 76 | + |
| 77 | + |
| 78 | +end |
| 79 | + |
| 80 | + |
| 81 | +defimpl String.Chars, for: CssColors.RGB do |
| 82 | +def to_string(struct) do |
| 83 | + Matplotex.Colorscheme.Rgb.to_string(struct) |
| 84 | +end |
| 85 | +end |
0 commit comments