Transparency in Processing

Your first few sketches in Processing might use simple grayscale. For example,

void setup() {
    size(640,480);
    background(50);
}


is a complete Processing program that opens a 640x480 window, and paints the window a dark gray. You can pass the background method a grayscale level from 0-255. Or you can pass three numbers, each from 0-255, representing red, green, and blue respectively. You can pass a single color number in hex (e.g. #FF0000 is red). Or you can pass four numbers 0-255, representing, red, green, blue, and alpha (transparency).

Here is a sketch that shows the effect of alpha as it ranges from 0 to 255. The code is provided below.



void setup() {
  size(480, 480);
}

void draw() {
  background(255);
  noStroke();
  //Rather than fixing alpha, let it cycle continuously from 0-255
  float alpha = 128 * (sin(millis() * 0.0005) + 1.0) ;
  float radius = height * 0.5;
  float topCircleCenterY = radius * .75;
  fill(255,0,0,alpha);
  ellipse(width/2, topCircleCenterY, radius, radius);
  fill(0,255,0,alpha);
  ellipse(width/2 - radius/3, topCircleCenterY + radius /2, radius,radius);
  fill(0,0,255,alpha);
  ellipse(width/2 + radius/3, topCircleCenterY + radius /2 , radius,radius);
  
  String msg = "alpha = "+((int)alpha);
  float tHeight = 32;
  textSize(tHeight);
  float tWidth = textWidth(msg);
  fill(150);
  text(msg, (width - tWidth)/2, tHeight);  

}

Comments are closed.