]> git.eshelyaron.com Git - emacs.git/commitdiff
Add color-blend to blend two RGB lists
authorJoseph Turner <joseph@breatheoutbreathe.in>
Sat, 2 Nov 2024 04:58:07 +0000 (21:58 -0700)
committerEshel Yaron <me@eshelyaron.com>
Sat, 9 Nov 2024 15:49:43 +0000 (16:49 +0100)
* lisp/color.el (color-blend): Blend two RGB lists.
* test/lisp/color-tests.el (color-tests-blend): Test color-blend.
* etc/NEWS: Announce color-blend.

(cherry picked from commit bf312529def48bc6fdf72d43d5be158d125f52f6)

etc/NEWS
lisp/color.el
test/lisp/color-tests.el

index 73f29b8800d4abc6bf2f9f6218fd398e132b50a6..133105e8a6c842d263da997745fea918dea85c00 100644 (file)
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -636,6 +636,11 @@ restore the old behavior, you can set 'eshell-pwd-convert-function' to
 This function natively-compiles all Lisp files in a directory and in its
 sub-directories, recursively, which were not already natively-compiled.
 
+---
+** New function 'color-blend'.
+This function takes two RGB lists and optional ALPHA and returns an RGB
+list whose elements are blended in linear space proportional to ALPHA.
+
 +++
 ** The 'defcustom' :local keyword can now be 'permanent-only'.
 This means that the variable's 'permanent-local' property is set to t,
index 007504043cc1e762bf42ca1cf77457311546b6e1..30e041c60a72b42cf66c08d1aa01be87f0ead796 100644 (file)
@@ -75,6 +75,22 @@ components (e.g. \"#ffff1212ecec\")."
           (- 1.0 (nth 1 color))
           (- 1.0 (nth 2 color)))))
 
+(defun color-blend (a b &optional alpha)
+  "Blend the two colors A and B in linear space with ALPHA.
+A and B should be lists (RED GREEN BLUE), where each element is
+between 0.0 and 1.0, inclusive.  ALPHA controls the influence A
+has on the result and should be between 0.0 and 1.0, inclusive.
+
+For instance:
+
+   (color-blend '(1 0.5 1) '(0 0 0) 0.75)
+      => (0.75 0.375 0.75)"
+  (setq alpha (or alpha 0.5))
+  (let (blend)
+    (dotimes (i 3)
+      (push (+ (* (nth i a) alpha) (* (nth i b) (- 1 alpha))) blend))
+    (nreverse blend)))
+
 (defun color-gradient (start stop step-number)
   "Return a list with STEP-NUMBER colors from START to STOP.
 The color list builds a color gradient starting at color START to
index 63cb024bb8dc0c7871f72e5e7ecb4fa826aa3263..3f7483a97c6a8d6b8b0c953e79831d8b1d166e32 100644 (file)
   (should (equal (color-complement "#ffffffffffff") '(0.0 0.0 0.0)))
   (should (equal (color-complement "red") '(0.0 1.0 1.0))))
 
+(ert-deftest color-tests-blend ()
+  (should (equal (color-blend '(1.0 0.0 0.0) '(0.0 1.0 0.0)) '(0.5 0.5 0.0)))
+  (should (equal (color-blend '(1.0 1.0 1.0) '(0.0 1.0 0.0)) '(0.5 1.0 0.5)))
+  (should (equal (color-blend '(0.0 0.39215686274509803 0.0) '(0.9607843137254902 0.8705882352941177 0.7019607843137254))
+                 '(0.4803921568627451 0.6313725490196078 0.3509803921568627))))
+
 (ert-deftest color-tests-gradient ()
   (should-not (color-gradient '(0 0 0) '(255 255 255) 0))
   (should