Individual stroke colours for each side of a rect

I was wondering if there was function that allows you to assign a unique colour value to each side of a rect - So for example the top stroke of a rect could be green and the bottom stroke of the rect could be red - I don’t know if this already exists but I looked through the references on the processing website but couldn’t seem to find anything.

Many thanks,
K

1 Like

I don’t think this exists out of the box, but you could create your own function that did this using the line() function.

I wasn’t sure from this description if you wanted flat color lines, or vertex shading (gradients between color points).

Here is an example of each, using PShape / beginShape.

/**
 * ColorRects
 * 2018-02-04 - Jeremy Douglass - Processing 3.4
 * Draw per-line coloring on rectangles using a list of colors.
 * Rendered using shape (PShape) in LINES mode. Flat and gradient lines.
 * discourse.processing.org/t/individual-stroke-colours-for-each-side-of-a-rect/7937
 */

int[] colors;

void setup() {
  size(200, 200, P2D);
  colors = new int[] {
    color(255,0,0),
    color(0,255,0),
    color(0,0,255),
    color(255)
  };
}
void draw() {
  background(128);
  colorRect(10,10,80,80,colors);
  colorRect2(110,110,80,80,colors);
}

void colorRect(float x, float y, float w, float h, int[] colors) {
  beginShape(LINES);
  stroke(colors[0]);
  vertex(x, y);
  vertex(x+w, y);
  stroke(colors[1]);
  vertex(x+w, y);
  vertex(x+w, y+h);
  stroke(colors[2]);
  vertex(x+w, y+h);
  vertex(x, y+h);
  stroke(colors[3]);
  vertex(x, y+h);
  vertex(x, y);
  endShape();
}

void colorRect2(float x, float y, float w, float h, int[] colors) {
  beginShape(LINES);
  stroke(colors[0]);
  vertex(x, y);
  stroke(colors[1]);
  vertex(x+w, y);
  vertex(x+w, y);
  stroke(colors[2]);
  vertex(x+w, y+h);
  vertex(x+w, y+h);
  stroke(colors[3]);
  vertex(x, y+h);
  vertex(x, y+h);
  stroke(colors[0]);
  vertex(x, y);
  endShape();
}

ColorRects--screenshot

Note that you could probably also do this using a PShader.

2 Likes

This is super helpful! Thank you!