简体   繁体   中英

How to make gradient color white - brown - green using Java Color

I am trying to make gradiend colour between :

White (light to dark)
Brown (dark to light
Green (dark to ligh)

But I don't know how to implement it.

My attempt was terrible, and so I ask you for help.

My try:

    for (int i = 255; i > 0; i--) {
        if (i > 230) {
            g2.setColor(new Color(0 + i, 0 + i, 0 + i));
        } else if (i <= 230 && i > 180) {
            g2.setColor(new Color(139 - (255 - i), 89 - (255 - i), 19));
        } else if (i <= 180 && i > 79) {
            g2.setColor(new Color(0, 60 + (180 - i), 0));
        } else {
            g2.setColor(Color.blue);
        }
        g2.drawLine(0, 255 - i, 500, 255 - i);
    }

Look:

GRADIENT IMAGE OUTPUT

Thank you for any help!

I think it should be a kind of:

for (int i = 255; i > 0; i--) {
    float h;
    float s;
    float v;
    if (i > 230) {
        h = 0;      // gray
        s = 0;
        v = 1f * i / 255;
    } else if (i <= 230 && i > 180) {
        h = 0.1;   // brown
        s = 0.8;
        v = 1f * (230 - i) / (230 - 180);
    } else if (i <= 180 && i > 79) {
        h = 0.33;  // green
        s = 1f;
        v = 1f * (180 - i) / (180 - 79);
    } else {
        h = 0.62;  // blue
        s = 1f;
        v = 1f;
    }
    g2.setColor(new Color(Color.HSBtoRGB(h, s, v)));
    g2.drawLine(0, 255 - i, 500, 255 - i);
}

The idea is to operate in HSV color space instead of RGB, where H (hue) and S (saturation) components determine position at color sircle, and V determines "value"--how far is the color from black point. So, you fix H and S components and vary V to make a color lighter or darker.

See: https://docs.oracle.com/javase/8/docs/api/java/awt/Color.html#HSBtoRGB-float-float-float-

If you find more appropriate h and s constants for each color, feel free to comment/edit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM