Skip to content

Commit

Permalink
Parse css hex string to color
Browse files Browse the repository at this point in the history
  • Loading branch information
anuragsoni committed Jul 18, 2018
1 parent 41d322b commit 3449ab9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/color.ml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,23 @@ let of_hsla h s l a =

let of_hsl h s l = of_hsla h s l 1.

let of_hexstring s =
if String.length s = 4 || String.length s = 7 then
let short = String.length s = 4 in
let r' = if short then String.sub s 1 1 else String.sub s 1 2 in
let g' = if short then String.sub s 2 1 else String.sub s 3 2 in
let b' = if short then String.sub s 3 1 else String.sub s 5 2 in
let r = int_of_string_opt ("0x" ^ r') in
let g = int_of_string_opt ("0x" ^ g') in
let b = int_of_string_opt ("0x" ^ b') in
match (r, g, b) with
| Some r, Some g, Some b ->
if short then
Some (of_rgb ((16 * r) + r) ((16 * g) + g) ((16 * b) + b))
else Some (of_rgb r g b)
| _ -> None
else None

let to_hsla (HSLA (h, s, l, a)) = {Hsla.h= clip_hue h; s; l; a}

let to_rgba' (HSLA (h, s, l, a)) =
Expand Down
5 changes: 5 additions & 0 deletions lib/color.mli
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ val of_hsl : float -> float -> float -> t
degrees, a float value between 0.0 and 360.0. Saturation and Lightness are float
values between 0.0 and 1.0 *)

val of_hexstring : string -> t option
(** Parse a hexadecimal color code. Handles short format like [#rgb] or
long format [#rrggbb]. Short format [#abc] corresponds to long format
[#aabbcc]. *)

val to_hsla : t -> Hsla.t
(** Converts a [color] to its Hue, Saturation, Lightness and Alpha values. *)

Expand Down

0 comments on commit 3449ab9

Please sign in to comment.