Search code examples
javaprocessinggradient

Create Colour Gradiente on Processing


I have a code to map out colours in order to create a radial gradient in a circle. Right know it's going from black to white. How can I switch up the colours, and use other values? I have tried to create values for different colours but it's not working. Does anyone knows how to do it? Here's the piece of code:

// function to draw the gradient
void desenhar_grad(float posX, float posY, int raio) {
  pushStyle();
  noStroke();
  for (int r = raio; r > 0; r--) {
    int tom = round(map(r, raio, 0, 255, 0)); // the last 2 values are the colours. first is the center, second is the exterior
    fill(tom);
    circle(posX, posY, r * 2);
  }
  popStyle();
}

Solution

  • Your method works great for grayscale colours.

    To easily interpolate between two colours with multiple channels you can use lerpColor(). It takes two colours as the first two arguments (colour to interpolate from and colour to interpolate to) and the first argument is the amount of interpolation (a value between 0.0 and 1.0 where 0 means it's the first colour, 1.0 is the second colour and 0.5 for example is a 50% mix between the two)

    You could then map r as you do already from in the 0.0 to 1.0 range:

    void setup(){
      desenhar_grad(50, 50, 50, color(0, 192, 192), color(192, 0, 192));
    }
    void desenhar_grad(float posX, float posY, int raio, color color1, color color2) {
      pushStyle();
      noStroke();
      for (int r = raio; r > 0; r--) {
        // the last 2 values are the colours. first is the center, second is the exterior
        int tom = lerpColor(color1, color2, map(r, 0, raio, 0.0, 1.0));
        fill(tom);
        circle(posX, posY, r * 2);
      }
      popStyle();
    }