From 8c3e96583b6c8248251c026edc730f6ff0b050d4 Mon Sep 17 00:00:00 2001 From: Joseph Turner Date: Fri, 1 Nov 2024 21:58:07 -0700 Subject: [PATCH 1/2] Add color-blend to blend two RGB lists * 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. --- etc/NEWS | 5 +++++ lisp/color.el | 16 ++++++++++++++++ test/lisp/color-tests.el | 6 ++++++ 3 files changed, 27 insertions(+) diff --git a/etc/NEWS b/etc/NEWS index 4aba4b17055..434732dfccf 100644 --- a/etc/NEWS +++ b/etc/NEWS @@ -685,6 +685,11 @@ single binding syntax, which we'd kept only for backwards compatibility. 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, diff --git a/lisp/color.el b/lisp/color.el index 79dced4e3d7..155b0dd54ca 100644 --- a/lisp/color.el +++ b/lisp/color.el @@ -75,6 +75,22 @@ color-complement (- 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 diff --git a/test/lisp/color-tests.el b/test/lisp/color-tests.el index 0f53e4332a4..2f874aa5958 100644 --- a/test/lisp/color-tests.el +++ b/test/lisp/color-tests.el @@ -62,6 +62,12 @@ color-tests-complement (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 -- 2.46.0