处理 PImage 数组保留在内存中



>我有一个简单的处理草图,其中图片被读入PImage数组。(按键小写字母)。如果我按大写字母,草图应该重置所有内容或至少使图像数组为零。但我无法完成这项工作。内存分配空间,其消耗不断增长。重置应用程序时,绘制调用仍会呈现图像(第 18 行)。这是我的代码:

PImage[] images;
PImage photo;
int counter;
void setup()
{
  //Storage of image replicas
  images = new PImage[0];
  //Image instance that gets copied on key press
  photo = loadImage("x.png");
  size(500, 500);  
}
void draw()
{
  //Image instance
  image(photo,0,0);
  for(int i= 0; i < images.length; i++){
    //copied instances from images
    image(images[i], i*50, 100);
  }
}
void keyPressed() {
  int keyIndex = -1;
  if (key >= 'a' && key <= 'z') {
    println("copy iamge and save in PImage Array");
    PImage tmpImg = get(0,0,50,50);
    images = (PImage[]) expand(images, images.length+1);
    images[counter] = tmpImg;
    counter++;
  }
  else if (key >= 'A' && key <= 'Z') {
    //attempt to reset image cache
    for (int i=0; i< images.length; i++) {
      println("attempt to reset cache");
      g.removeCache(images[i]);
    }
    println("attempt to reset PImage Array");
    images = null;
    images = new PImage[0];
    counter = 0;
    //attempt to call setup to reset PImage Array
    setup();
  }
}

任何帮助都非常感谢!

处理不会自动清除旧帧 - 它只是在存在的任何内容之上绘制。你可以用这个小草图证明这一点:

void draw(){
  ellipse(mouseX, mouseY, 10, 10);
}

要清除旧帧,您必须专门告诉 Processing 绘制背景,如下所示:

void draw(){
  background(0);
  ellipse(mouseX, mouseY, 10, 10);
}

您的代码实际上是清除旧图像,但您永远不会清除旧帧,因此它们仍然可见。

只需在 draw() 函数的第一行调用 background() 函数。

至于您的内存使用量上升,这可能是正常的。您的内存是否不足,或者垃圾回收器最终会启动?

最新更新