Skip to content

Instantly share code, notes, and snippets.

@KrabCode
Created May 26, 2020 15:30
Show Gist options
  • Select an option

  • Save KrabCode/866f7ecb7e53e82d5fa6fa15984c38a0 to your computer and use it in GitHub Desktop.

Select an option

Save KrabCode/866f7ecb7e53e82d5fa6fa15984c38a0 to your computer and use it in GitHub Desktop.
Adjustable color gradient with manual interpolation without using Processing's triangle strips.
void setup() {
size(800, 800, P2D);
}
void draw() {
float[] positions = new float[]{0, 0.25, 0.5, 0.55, 1};
int[] colors = new int[]{
color(0),
color(4, 38, 102),
color(255, 255, 255),
color(68, 144, 201),
color(0)
};
ramp(positions, colors);
}
protected void ramp(float[] positions, int[] colors) {
if (positions.length != colors.length) {
throw new IllegalArgumentException();
}
for (int y = 0; y < height; y++) {
int prevPosIndex = 0;
int nextPosIndex = 1;
float yNorm = norm(y, 0, height);
for (int i = 1; i < positions.length; i++) {
float pos = positions[i];
if (yNorm >= pos) {
prevPosIndex = i;
nextPosIndex = i+1;
}
}
float yNormalizedBetweenPrevAndNextPos = norm(yNorm, positions[prevPosIndex], positions[nextPosIndex]);
int interpolatedColor = lerpColor(colors[prevPosIndex], colors[nextPosIndex], yNormalizedBetweenPrevAndNextPos);
stroke(interpolatedColor);
line(0, y, width, y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment