理解处理中的void draw()

Oma*_*mar 3 processing draw

我正在修补处理,无法弄清楚如何在我使用图像缓冲区(旋转方块)创建的图像上写入文本...当正方形变得比文本小时,变化的数字在彼此之上写入.无法使用重置bkg作为解决方案,因为这会擦除重叠的图像.仍然很难理解这个领域......

问题:如何使文本显示在旋转方块的顶部而不重置bkg并且不将文本写在自身上

代码如下谢谢!

float rotateAmount;
int boxColorR = 255;
int boxColorG = 255;
int boxColorB = 255;
int boxW = 480;
void setup () {
  size(640,480);
  rectMode(CENTER);

}

void drawText() {
  //translate(width/2,height/2);
  textAlign(LEFT, CENTER);
  fill(255, 255, 255);
  textSize(32);
  text("RED: " + boxColorR,width/2,height/2);
  text("GREEN: " + boxColorG,width/2,height/2+30);
  text("BLUE: " + boxColorB,width/2,height/2+60);
  text("Box Width: " + boxW,width/2,height/2+90); 
}

void drawBox() {
  translate(width/2,height/2);
    rotateAmount += 12;
    if (boxColorR <= 0) {
    boxColorG--;
  }
    if (boxColorG <= 0) {
    boxColorB--;
  }
  boxColorR--;
  boxW--;
  rotateAmount += .05;
  rotate(rotateAmount);
  fill(boxColorR,boxColorG,boxColorB);
  rect(0,0,boxW,boxW);
  resetMatrix();

}



void draw() {
    //rect(width/2,height/2,640,480); //this solves the text overlapping but erases the cool effect
    drawBox();
    drawText();

}
Run Code Online (Sandbox Code Playgroud)

Kev*_*man 5

大多数Processing草图使用对background()函数的调用作为draw()函数的第一行.这清除了先前帧中绘制的任何内容.

但是,您希望保留先前帧中绘制的内容,因此您不希望将其清除.这样做的问题是,由于您的文本也没有被清除,您的文本最终看起来很乱.

解决方案是使用PGraphics类创建一个屏幕外缓冲区.您将方块绘制到缓冲区而不是屏幕.然后将缓冲区绘制到屏幕上,最后,在缓冲区顶部绘制文本.

由于您在每个帧中将缓冲区绘制到屏幕上,因此它会清除旧文本,但您之前绘制的方块将保留在缓冲区中.

代码比单词更响亮:

float rotateAmount;
int boxColorR = 255;
int boxColorG = 255;
int boxColorB = 255;
int boxW = 480;

//create a buffer to draw boxes to
PGraphics buffer;

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

  buffer = createGraphics(640, 480);
}

void drawText() {
  //translate(width/2,height/2);
  textAlign(LEFT, CENTER);
  fill(255, 255, 255);
  textSize(32);
  text("RED: " + boxColorR, width/2, height/2);
  text("GREEN: " + boxColorG, width/2, height/2+30);
  text("BLUE: " + boxColorB, width/2, height/2+60);
  text("Box Width: " + boxW, width/2, height/2+90);
}

//draw boxes to buffer
void drawBox() {

  buffer.beginDraw();
  buffer.rectMode(CENTER);

  buffer.translate(width/2, height/2);
  rotateAmount += 12;
  if (boxColorR <= 0) {
    boxColorG--;
  }
  if (boxColorG <= 0) {
    boxColorB--;
  }
  boxColorR--;
  boxW--;
  rotateAmount += .05;
  buffer.rotate(rotateAmount);
  buffer.fill(boxColorR, boxColorG, boxColorB);
  buffer.rect(0, 0, boxW, boxW);
  buffer.resetMatrix();

  buffer.endDraw();
}

void draw() {

  //draw the boxes to the buffer
  drawBox();
  //draw the buffer to the screen
  image(buffer, 0, 0);

  //draw the text on top of the buffer
  drawText();
}
Run Code Online (Sandbox Code Playgroud)