【问题标题】:How to modify color intensity in a java swing application如何在 java swing 应用程序中修改颜色强度
【发布时间】:2014-09-06 19:25:43
【问题描述】:

我正在使用 java swing 来创建一个用户在其中绘制几个点的界面。我想要做的是在绘制这些点之后自动改变颜色的强度,从非常亮到暗,直到点消失。有谁知道有关如何更改颜色强度的任何教程,因为我找不到可以帮助我的东西。

编辑:感谢您的回答,他们帮助我更好地理解了如何使用 Color 类。我修复了它,所以我正在上传线程部分以帮助其他人是否需要做类似的事情......我正在处理黑色背景,所以我将颜色变暗而不是变亮。

public class MyThread extends Thread {

    private Canvas canvas;
    private int sleepingTime = 5000;
    private Color color;
    private int red, green, blue, alpha;

    public MyThread(Canvas canvas) {
        super();
        this.canvas = canvas;
        setDaemon(true);

    }

    public void run(){
        while (true){
            try {
                System.out.println("going to sleep...");
                Thread.sleep(sleepingTime);

            } catch (InterruptedException e) {
                System.out.println("sleep interrupted..");
                return;
            }
            System.out.println("woke up!");
                int size = canvas.points_list.size();
                int i =0;
                while (size > 0) {
                    color = canvas.points_list.get(i).getForeground();

                    red = (int) Math.round(Math.max(0, color.getRed() - 255 * 0.25f));
                    green = (int) Math.round(Math.max(0, color.getGreen() - 255 * 0.25f));
                    blue = (int) Math.round(Math.max(0, color.getBlue() - 255 * 0.25f));

                    alpha = color.getAlpha();

                    canvas.points_list.get(i).setForeground(new Color(red, green, blue, alpha));
                    size--; 
                    i++;
                }

                canvas.repaint();
        }
    }
}

【问题讨论】:

  • 对于example,您可以通过多种方式实现这一目标
  • 或者这个example使用Color.getHSBColor()
  • 要淡化颜色,我会增加 alpha 分量。

标签: java swing colors brightness


【解决方案1】:

您需要使用 RGB 形式,通过添加蓝色和绿色并保持红色值相同,使其成为从亮到暗的渐变,在 for 循环中不断执行此操作,然后最后将其设置为背景颜色让它不可见。

【讨论】:

    【解决方案2】:

    看看 HSB 颜色模型。它允许您指定“强度”(饱和度和亮度)。

    示例(红色背景变为黑色 - 或者,修改“s”参数以将颜色淡化为白色):

    final Frame frame = new Frame();
    
    Timer timer = new Timer(500, new ActionListener() {
    
        float b = 1.0f;
    
        @Override
        public void actionPerformed(ActionEvent e) {
            int color = Color.HSBtoRGB(0, 1, b);
            frame.setBackground(new Color(color));
    
            b -= 0.05f;
        }
    });
    timer.start();
    
    frame.setSize(200, 200);
    frame.setVisible(true);
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 2020-12-11
      • 2011-05-06
      • 1970-01-01
      • 2016-09-27
      • 2010-11-23
      相关资源
      最近更新 更多