Leonardo Leonardo - 4 years ago 170
Java Question

How to draw a RGB Color Wheel in Java

I am trying to draw a RGB color wheel in Java, but I can't get the gradient by a circular shape. I just want to draw it on screen, with no user interaction at all.

This is all I have for now:

public void paint (Graphics g){
super.paint(g);

int red = 255;
int green = 0;
int blue = 0;
int x1 = 500;
int y1 = 305;
int x2 = 500;
int y2 = 50;

while (green != 255){
g.setColor(new Color(red, green, blue));
green++;
g.drawLine(x1, y1, x2, y2);
x2++;
if (y2 < y1){
y2++;
}
}
while (red != 0){
g.setColor(new Color(red, green, blue));
red--;
g.drawLine(x1, y1, x2, y2);
x2--;
y2++;
}
x2 = 500;
while (blue != 255){
g.setColor(new Color(red, green, blue));
blue++;
g.drawLine(x1, y1, x2, y2);
x2--;
if (y2 > y1){
y2--;
}
}

while (red != 255){
green--;
g.setColor(new Color(red, green, blue));
red++;
g.drawLine(x1, y1, x2, y2);
x2++;
y2--;
}
}
}


Which draws the gradient like this

This is what I want

Answer Source

Changing Brightness

From here, it seems like the easiest way to brighten a color is by converting it to HSB.

float hsbVals[] = Color.RGBtoHSB( originalColor.getRed(),
                                   originalColor.getGreen(),
                                   originalColor.getBlue(), null );

    Color highlight = Color.getHSBColor( hsbVals[0], hsbVals[1], 
      0.5f * ( 1f + hsbVals[2] )); // Play with this part to modify rate of change

Making it circular

From what you have, it looks like you essentially need to erase all but a circular region in the middle.

From this answer, it seems like the Area class is easiest.

 public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D)g.create();
        Rectangle2D rectangleNotToDrawIn = new Rectangle2D.Double(100, 100, 20, 30); 
           // You will need to find out what size ellipse you need
        Area outside = calculateOutside(rectangleNotToDrawIn);

        // draw color wheel here

        g2.setPaint(Color.black); // assuming you want black
        g2.setClip(outside);
        g2.drawLine(0, 0, getWidth(), getHeight());

    }

// Change this method to take in an ellipse shape.
    private Area calculateOutside(Rectangle2D r) {
        Area outside = new Area(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
        outside.subtract(new Area(r));
        return outside;
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download