Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Gradient colors

Name: Anonymous 2010-05-05 23:24

How would I write a function that would take two colors: (255,0,0), and (0,0,255), a value from 0.0 to 1.0, and have it output the color in between the first two based on that number.  Like, if I ran this function like this:

gradient((255,0,0),(0,0,255),0.5)


it would return


(128,0,128)

Name: Anonymous 2010-05-05 23:30


r = r1*p+r2*(p-1);
g = g1*p+g2*(p-1);
b = b1*p+b2*(p-1);


...isn't it obvious?

Name: Anonymous 2010-05-05 23:31

>>2
fuck. try this instead
r = r1*p+r2*(1-p);
g = g1*p+g2*(1-p);
b = b1*p+b2*(1-p);

Name: Anonymous 2010-05-05 23:48

>>3
gradient = lambda c1, c2, pos: [int(n * pos + m * (1 - pos)) for m, n in zip(c1, c2)]

Name: Anonymous 2010-05-06 0:46

Just scale a matrix transform. Bonus points for doing it in hardware.

Name: Anonymous 2010-05-06 3:37


typedef struct {
    int r;
    int g;
    int b;
} color;

color calculateGradient(color c1, color c2, float percentage)
{
   color delta = {c2.r - c1.r, c2.g - c1.g, c2.b - c1.b};
   color retval = {(int) c1.r + percentage * delta.r,
                   (int) c1.g + percentage * delta.g,
                   (int) c1.b + percentage * delta.b};
   return retval;
}

Name: Anonymous 2010-05-06 3:50

#include <stdio.h>

typedef float v4sf __attribute__ ((vector_size (4 * sizeof(float))));

typedef union
{ v4sf v;
  float f[4]; } f4vector;

v4sf gradient(v4sf c1, v4sf c2, float p)
{ float q = 1 - p;
  return c1 * (v4sf){p, p, p, p} + c2 * (v4sf){q, q, q, q}; }

int main(void)
{ f4vector c3 = { .v = gradient((v4sf){255, 0, 0}, (v4sf){0, 0, 255} , 0.5) };
  printf("%f %f %f\n", c3.f[0], c3.f[1], c3.f[2]);
  return 0; }

Name: Anonymous 2010-05-06 4:28


(defun normalize-rgb (x)
  (round (mod x 256)))

(defun gradient (seq1 seq2 alpha
                 &key (key #'normalize-rgb)
                 &aux (alpha-inv (1- alpha)))
  (map 'vector #'(lambda (v1 v2)
                   (funcall key
                     (+ (* v1 alpha) (* v2 alpha-inv))))
       seq1 seq2))

(gradient #(255 0 0) #(0 0 255) 0.5) ;=> #(128 0 128)

Name: Anonymous 2010-11-03 3:19

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List