color.scm 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. (define-module (basket color)
  2. #:use-module (basket)
  3. #:use-module (srfi srfi-1))
  4. (export
  5. hsl->rgb
  6. hsv->rgb)
  7. (define (preserve-alpha fn color)
  8. (if (<= (length color) 3)
  9. (fn color)
  10. (append (fn (take color 3)) (drop color 3))))
  11. (define (hsl->rgb' hsl)
  12. (let* ((h (car hsl))
  13. (s (cadr hsl))
  14. (l (caddr hsl))
  15. (c (* s (- 1 (abs (- (* 2 l) 1)))))
  16. (hh (* 6 h))
  17. (x (* c (- 1 (abs (- (floor-remainder hh 2) 1))))))
  18. (map (curry + (- l (/ c 2)))
  19. (cond
  20. ((< hh 1) (list c x 0))
  21. ((< hh 2) (list x c 0))
  22. ((< hh 3) (list 0 c x))
  23. ((< hh 4) (list 0 x c))
  24. ((< hh 5) (list x 0 c))
  25. ((<= hh 6) (list c 0 x))
  26. (else (list 0 0 0))))))
  27. (define (hsl->rgb hsl)
  28. "Converts a color from HSL(A) to RGB(A)."
  29. (preserve-alpha hsl->rgb' hsl))
  30. (define (hsv->rgb' hsv)
  31. (let* ((h (car hsv))
  32. (s (cadr hsv))
  33. (v (caddr hsv))
  34. (c (* v s))
  35. (hh (* 6 h))
  36. (x (* c (- 1 (abs (- (floor-remainder hh 2) 1))))))
  37. (map (curry + (- v c))
  38. (cond
  39. ((< hh 1) (list c x 0))
  40. ((< hh 2) (list x c 0))
  41. ((< hh 3) (list 0 c x))
  42. ((< hh 4) (list 0 x c))
  43. ((< hh 5) (list x 0 c))
  44. ((<= hh 6) (list c 0 x))
  45. (else (list 0 0 0))))))
  46. (define (hsv->rgb hsv)
  47. "Converts a color from HSV(A) to RGB(A)."
  48. (preserve-alpha hsv->rgb' hsv))