如何在 mousePressed 后保持 fill() 中的颜色相同?

How to keep a color in a fill() the same after mousePressed?

在单击(即更改时)然后取消单击并悬停后保持 fill() 不变的最简单方法是什么?

在这个项目中,我只是做了一个网格。当鼠标悬停在特定的矩形(xy)上时,它会根据它所处的状态改变颜色。fill(50) 是默认值,fill(75) 是当鼠标悬停,fill(100)是鼠标点击的时候。但是这里当鼠标未被点击时它 returns 悬停填充直到鼠标离开矩形。谢谢。

int cols, rows;
int scl = 20;

void setup() {
size(400, 400);
int w = 400;
int h = 400;
cols = w / scl;
rows = h / scl;
}

void draw() {
background(255);

  for (int x = 0; x < cols; x++) {
    for (int y = 0; y < rows; y++) {
      int xpos = x*scl;
      int ypos = y*scl;
      stroke(55);
      if((mouseX >= xpos && mouseX <= xpos+scl) &&
        (mouseY >= ypos && mouseY <= ypos+scl)){
        fill(75);
        if (mousePressed == true){
          println("Clicked at: " + xpos + " and " + ypos);
          fill(100);
        //here is the desired location for the fill to remain constant even 
        //after unclicking and leaving hover
        }
        println("Mouse at: " + xpos + " and " + ypos);
      }else{
        fill(50);
      }

      rect(xpos, ypos, scl, scl);
    }
  }
}

Stack Overflow 并不是真正为一般 "how do I do this" 类型的问题设计的。这是针对特定 "I tried X, expected Y, but got Z instead" 类型的问题。但我会尽力提供一般意义上的帮助:

您需要将每个单元格的状态存储在一个数据结构中,然后使用该数据结构来绘制您的场景。

您可以使用二维数组执行此操作,其中数组中的每个单元格代表网格中的一个单元格。您可以存储单元格的状态,或直接存储颜色。

正如凯文所说,您应该将应用程序的状态保存在矩阵中。

boolean[][] matrix = new boolean[21][21];

当您点击 cell 时,切换它

if(!matrix[xpos/scl][ypos/scl]) {
    matrix[xpos/scl][ypos/scl] = true;
} else {
    matrix[xpos/scl][ypos/scl] = false;
}

在此循环中,检查您当前的位置是否可以绘制

if(matrix[x][y]) {
    fill(204, 102, 0); // an orange color
    rect(xpos, ypos, scl, scl);
}

所以您的 draw() 方法应该如下所示

void draw() {
    background(255);
    for (int x = 0; x < cols; x++) {
        for (int y = 0; y < rows; y++) {
            int xpos = x*scl;
            int ypos = y*scl;

            stroke(55);
            if((mouseX >= xpos && mouseX <= xpos+scl) &&
                    (mouseY >= ypos && mouseY <= ypos+scl)){
                fill(75);
                if (mousePressed == true){
                    println("Clicked at: " + xpos + " and " + ypos);
                    if(!matrix[xpos/scl][ypos/scl]) {
                        matrix[xpos/scl][ypos/scl] = true;
                    } else {
                        matrix[xpos/scl][ypos/scl] = false;
                    }
                    fill(100);
                    //here is the desired location for the fill to remain constant even 
                    //after unclicking and leaving hover
                }
                println("Mouse at: " + xpos + " and " + ypos);
            }else{
                fill(50);
            }
            if(matrix[x][y]) {
                fill(204, 102, 0);
                rect(xpos, ypos, scl, scl);
            }
            rect(xpos, ypos, scl, scl);
        }
    }
}