【问题标题】:How to generate random bright color?如何生成随机的亮色?
【发布时间】:2016-08-08 12:24:50
【问题描述】:

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

【问题讨论】:

标签: java swing random colors


【解决方案1】:

使用 Color 类静态方法getHSBColor(...),并确保第三个参数,即代表亮度的参数对您来说足够高,可能 > 0.8f(但

例如下面的代码使用上面的方法找一个随机的亮色:

    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 到 255 之间的随机数。

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 2010-12-07
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多