Simple Linear Gradient

Simple Linear Gradient

The lerpColor() function is useful for interpolating between two colors.


// Constants
int Y_AXIS = 1;
int X_AXIS = 2;
color b1, b2, c1, c2;

void setup() {
  size(640, 360);

  // Define colors
  b1 = color(255);
  b2 = color(0);
  c1 = color(204, 102, 0);
  c2 = color(0, 102, 153);

  noLoop();
}

void draw() {
  // Background
  setGradient(0, 0, width/2, height, b1, b2, X_AXIS);
  setGradient(width/2, 0, width/2, height, b2, b1, X_AXIS);
  // Foreground
  setGradient(50, 90, 540, 80, c1, c2, Y_AXIS);
  setGradient(50, 190, 540, 80, c2, c1, X_AXIS);
}

void setGradient(int x, int y, float w, float h, color c1, color c2, int axis ) {

  noFill();

  if (axis == Y_AXIS) {  // Top to bottom gradient
    for (int i = y; i <= y+h; i++) {
      float inter = map(i, y, y+h, 0, 1);
      color c = lerpColor(c1, c2, inter);
      stroke(c);
      line(x, i, x+w, i);
    }
  }  
  else if (axis == X_AXIS) {  // Left to right gradient
    for (int i = x; i <= x+w; i++) {
      float inter = map(i, x, x+w, 0, 1);
      color c = lerpColor(c1, c2, inter);
      stroke(c);
      line(i, y, i, y+h);
    }
  }
}

Functions Used

stroke()

Sets the color used to draw lines and borders around shapes

Learn More
size()

Defines the dimension of the display window width and height in units of pixels

Learn More
lerpColor()

Calculates a color between two colors at a specific increment

Learn More
setup()

The setup() function is run once, when the program starts

Learn More
map()

Re-maps a number from one range to another

Learn More
color()

Creates colors for storing in variables of the color datatype

Learn More
noLoop()

Stops Processing from continuously executing the code within draw()

Learn More
draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More
noFill()

Disables filling geometry

Learn More
line()

Draws a line (a direct path between two points) to the screen

Learn More