计算形状数组的累积面积

Calculating the accumulated area of an array of shapes

我正在尝试计算每次创建矩形的累积面积。 我知道每次创建矩形时如何计算面积,但我希望总计 运行。 谢谢!

float[] p1x = new float[0]; // hold the mouse pressed marks
float[] p1y = new float[0];
float[] p1z = new float[0];
float[] p2x = new float[0]; // hold the mouse pressed marks
float[] p2y = new float[0];
float[] p2z = new float[0];
int count = 0;

int rect_x1; // catch the start dragging point x
int rect_y1; // catch the start dragging point y
int rect_x2; // record  moving mouseX
int rect_y2; // record moving mouseY
int rect_z1; // record mouseX releasing point
int rect_z2; // record mouseY releasing point.

boolean press, release, drag, drawRect;

void setup() {
    smooth();
    size(600, 400);
    stroke(255);
    fill(255, 255, 255, 10);
}

void draw() {
    background(50);
    Rect();
}

void Rect() {

    float sizex = rect_x2 - rect_x1;
    float sizey = rect_y2 - rect_y1;
    for (int i = 0; i < count; i++) {
        beginShape();
        vertex(p1x[i], p1y[i]);
        vertex(p2x[i], p1y[i]);
        vertex(p2x[i], p2y[i]);
        vertex(p1x[i], p2y[i]);
        endShape(CLOSE);
    }
    if (mousePressed && mouseButton == LEFT) {
        rect(rect_x1, rect_y1, sizex, sizey);
    }
}


void mousePressed() {
    p1x = append(p1x, mouseX);
    p1y = append(p1y, mouseY);
    rect_x1 = mouseX;
    rect_y1 = mouseY;
    mouseDragged(); // Reset vars

}

void mouseReleased() {
    p2x = append(p2x, mouseX);
    p2y = append(p2y, mouseY);
    rect_x2 = mouseX;
    rect_y2 = mouseY;
    count++;
}

void mouseDragged() {
    rect_x2 = mouseX;
    rect_y2 = mouseY;
}

嗯,你有几个选择。

选项 1:每次绘制矩形时计算总数。您的 Rect() 函数中有一个 for 循环,它循环并绘制它们。你可以直接计算总面积。

选项 2: 保持 运行 总数,并在每次添加矩形时递增。您可以在 mouseReleased() 函数中执行此操作。

当你说你想要一个累积的数字时,我不确定你的意思。您要么必须在需要总计时将它们合计,要么需要保留 运行 总计并在添加新矩形时添加。