如何生成随机的亮色?

Joh*_*reg 2 java random swing colors

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

Hov*_*els 5

使用 Color 类静态方法getHSBColor(...),并确保第三个参数,即表示亮度的参数对您来说足够高,可能 > 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);
Run Code Online (Sandbox Code Playgroud)

使用名为 random 的 Random 变量和 0.8f 的 MIN_BRIGHTNESS 值:

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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:或者如果您希望颜色完全饱和,请将饱和度参数更改为 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;
}
Run Code Online (Sandbox Code Playgroud)

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