Setting Alpha-Channel with PShape

edited December 2014 in How To...

Hi!

I use a PGraphics Object to store a sprite. When I draw the PGraphics Object on the screen, the regions I did not draw anything in appear transparent. Is it possible to delete a filled region in the PGraphics Object, using a PShape so that it appears transparent again?

Best regards,

Thorsten

Answers

  • Draw the PShape to a second PGraphics and use that to mask the primary PGraphics?

  • edited December 2014

    Hello ! I don't understand...

    "the regions I did not draw anything in appear transparent"

    "so that it appears transparent again"

    It's transparent or not ?

  • edited December 2014

    Proof of Concept

    PGraphics main, mask;
    PShape shape;
    
    void setup() {
      size(800, 600, P2D);
    
      // the main PGraphics has a RED background
      main = createGraphics(width, height, JAVA2D);
      main.beginDraw();
      main.background(255, 0, 0);
      main.endDraw();
    
      mask = createGraphics(width, height, JAVA2D);
    
      shape = createShape(ELLIPSE, -150, -150, 300, 300);
      shape.setStroke(false);
    }
    
    void draw() {
      // behind the main PGraphics are a GREEN background
      // and a BLUE rectangle moving from left to right 
      background(0, 255, 0);
      noStroke();
      fill(0, 0, 255);
      rect(frameCount % width, 0, 100, height);
      // display the main PGraphics
      image(main, 0, 0);
      // display the PShape
      shape(shape, mouseX, mouseY);
    }
    
    void mousePressed() {
      // clear the mask and draw the PShape to it
      mask.beginDraw();
      mask.clear();
      mask.shape(shape, mouseX, mouseY);
      mask.endDraw();
    
      // define transparant color ONCE
      color transparent = color(0, 0);
      main.loadPixels();
      mask.loadPixels();
      // go over all the pixels in the mask
      for (int i=0; i<mask.pixels.length; i++) {
        // get transparency of mask pixel
        int a = (mask.pixels[i] >> 24) & 0xFF;
        // if it is not transparenct (aka something is drawn on the mask)
        if (a > 0) {
          // make the main pixel in this location transparent
          main.pixels[i] = transparent;
        }
      }
      main.updatePixels();
    }
    
    void keyPressed() {
      // press SPACE to refill the main PGraphics with RED
      if (key == ' ') {
        main.beginDraw();
        main.background(255, 0, 0);
        main.endDraw();
      }
    }
    
Sign In or Register to comment.