I’ve been playing around a bit with Processing.org – a kinda-graphical programming language. One of the effect that I wanted to play with was a kind of radial transparency – a blob of colour that faded out toward the edges. After playing around for a while with drawing multiple ellipses, I settled on a pixel-based subroutine.

We create a new PGraphics object to hold the blob, then for each pixel calculate the distance from the centre as a proportion of the radius using the handy Math.hypot() method. Then, to get nice smooth fade-outs near the edges, we invert it to get the distance from the edge and then use the square of that value to determine the transparency. This gives a smoother effect – if we don’t use the square then the edges don’t transition smoothly (probably something to do with the sensitivity of human vision / LCD monitors to colour being non-linear). Anyway, here’s the code:

UPDATE – turns out that using Math.hypot() is very slow – switching to Math.sqrt() speeds up the code x10. The new code is below.

void radialGradient(float x, float y, int c, int size) {
  PGraphics pg = createGraphics(size, size, JAVA2D);
  pg.background(30, 0);
  int halfsize = size / 2;

    for (int i = 0; i <= size; i += 1) {
    for (int j = 0; j <= size; j += 1) {
      // calculate distance to center
      //float distance = (float) Math.hypot(i - size / 2, j - size / 2) / (size / 2);
      //float distance = (float) sqrt(sq(i-size/2) + sq(j-size/2)) / (size/2);
      float xDist = i - halfsize;
                float yDist =  j - halfsize;
                float distance = (float) Math.sqrt(xDist*xDist + yDist*yDist) / halfsize;
      float scale = 1 - distance;
      if (scale < 0 ) {
        scale = 0;
      float transparency = 255 * (scale * scale);
      int thisColour = color(c, int(transparency));
      pg.set(i, j, thisColour);

  image(pg, x, y);

Subscribe to articles from the programming category via RSS or ATOM


comments powered by Disqus