鼠标释放后填充的矩形消失

Filled rect disappear after mouse releasing

我是处理新手。我想写一个程序,其中我 select 一个图像区域(例如 Photoshop 中的“rect selection”......),这个区域有一个红色笔划并且有点不透明,一次该区域是 selected,矩形填充同一区域像素的平均颜色,红色描边关闭。这个想法是能够在同一张图像上多次重复这个动作。当我松开鼠标时,由于void draw();中的background(buff);,填充被擦除。我想保存填充有新颜色的矩形。我想我需要使用一个数组,class,但我不明白它们是如何工作的。如果有人能够帮助我,那将是一个很大的帮助。谢谢。

PImage buff1;
int x1,y1,x2,y2,h1,h2;

void setup()
{
    size(1000, 721);
    buff1 = loadImage("buff1.jpg2);
    background(buff1);
}

color extractColorFromImage(final PImage buff1) {
    buff1.loadPixels();
    color r = 1, g = 1, b = 1;

    for (final color c : buff1.pixels) {
        r += c >> 020 & 255;
        g += c >> 010 & 255;
        b += c & 255;
    }
    r /= buff1.pixels.length;
    g /= buff1.pixels.length;
    b /= buff1.pixels.length;
    return color(r, g, b);
}

void draw()
{
    background(buff1);
    rectMode(CORNERS);
    stroke(255,0,0);
    strokeWeight(2);
    strokeJoin(ROUND);
    rect(x1,y1,x2,y2,2);
    fill(255,0,0,50);
    noStroke();
    cursor(ARROW);
}

void mousePressed()
{
    x1 = mouseX;
    y1 = mouseY;
}

void mouseDragged()
{
    x2 = mouseX;
    y2 = mouseY;
}

void mouseReleased()
{
    int H1 = abs(1+x2-x1);
    int H2 = abs(1+y2-y1);

    for (int i=0; i<width; i+=H1)
    {
        for (int j=0; j<height; j+=H2)
        {
            PImage newImg = buff1.get(x1, y1, H1, H2);
            fill(extractColorFromImage(newImg), 40);
            noStroke();
            cursor(ARROW);
        }
    }
}

一旦图像的像素数据被 loadPixels(), the loaded pixels can be accessed and changed by pixels[] 加载。
updatePixels() 使用其 pixels[] 数组中的数据更新图像:

void mouseReleased()
{
    int x_1 = min(x1,x2);
    int y_1 = min(y1,y2);
    int x_2 = max(x1,x2);
    int y_2 = max(y1,y2);

    PImage newImg = buff1.get(x_1, y_1, x_2-x1+1, y_2-y1+1);
    color new_color = extractColorFromImage(newImg);

    buff1.loadPixels();
    for (int i = x_1; i <= x_2; i++)
    {
        for (int j = y_1; j <= y_2; j++)
        {
             buff1.pixels[j*buff1.width+i] = new_color;
        }
    }
    buff1.updatePixels();
}

当鼠标键按下时,那么我建议也设置(x2,y2):

void mousePressed()
{
    x1 = mouseX;
    y1 = mouseY;
    x2 = x1;
    y2 = y1;
}


可以选择将原始颜色与新颜色混合 lerpColor():

PImage newImg = buff1.get(x_1, y_1, x_2-x1+1, y_2-y1+1);
color new_color = extractColorFromImage(newImg);

buff1.loadPixels();
for (int i = x_1; i <= x_2; i++)
{
    for (int j = y_1; j <= y_2; j++)
    {
         color orig_color = buff1.pixels[j*buff1.width+i];
         buff1.pixels[j*buff1.width+i] = lerpColor(orig_color, new_color, 0.5); 
    }
}
buff1.updatePixels();