如何生成随机亮色?

时间:2016-04-16 14:49:12

标签: java swing random colors

我需要在Swing GUI中随机生成颜色,但问题是我希望它们只是很亮。

1 个答案:

答案 0 :(得分:3)

使用Color类静态方法getHSBColor(...),并确保第三个参数,即代表亮度的参数对您来说足够高,也许&gt; 0.8f(但<1.0f)。

例如,下面的代码使用上述方法查找随机亮色:

    float h = random.nextFloat();
    float s = random.nextFloat();
    float b = MIN_BRIGHTNESS + ((1f - MIN_BRIGHTNESS) * random.nextFloat());
    Color c = Color.getHSBColor(h, s, b);

使用名为random的随机变量,以及MIN_BRIGHTNESS值0.8f:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.*;

public class RandomBrightColors extends JPanel {
    private static final int PREF_W = 500;
    private static final int PREF_H = PREF_W;
    private static final int RECT_W = 30;
    private static final int RECT_H = RECT_W;
    private static final float MIN_BRIGHTNESS = 0.8f;
    private Random random = new Random();

    public RandomBrightColors() {
        setBackground(Color.BLACK);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < 100; i++) {
            g.setColor(createRandomBrightColor());
            int x = random.nextInt(getWidth() - RECT_W);
            int y = random.nextInt(getHeight() - RECT_H);
            g.fillRect(x, y, RECT_W, RECT_H);
        }
    }

    private Color createRandomBrightColor() {
        float h = random.nextFloat();
        float s = random.nextFloat();
        float b = MIN_BRIGHTNESS + ((1f - MIN_BRIGHTNESS) * random.nextFloat());
        Color c = Color.getHSBColor(h, s, b);
        return c;
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        RandomBrightColors mainPanel = new RandomBrightColors();

        JFrame frame = new JFrame("RandomBrightColors");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}

编辑:或者如果您希望颜色完全饱和,请将饱和度参数更改为1f:

private Color createRandomBrightColor() {
    float h = random.nextFloat();
    float s = 1f;
    float b = MIN_BRIGHTNESS + ((1f - MIN_BRIGHTNESS) * random.nextFloat());
    Color c = Color.getHSBColor(h, s, b);
    return c;
}

另请注意,这可以使用3 int参数RGB颜色来完成,但是如果这样做,请注意一个参数应接近但不超过255,一个应接近但不低于0,另一个参数应接近但不低于0可以是0到255之间的随机任何东西。