如何在 Java 中将 RGB 值添加到 setColor() 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42855224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:28:22  来源:igfitidea点击:

How to add RGB values into setColor() in Java?

javargb

提问by Austin Grant

How can I add (red, green, blue) values to my Java? For example:

如何将(红色、绿色、蓝色)值添加到我的 Java 中?例如:

 setColor(255, 0, 0);

The context looks like this:

上下文如下所示:

public void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();

    g.setColor(); // <-- This line
    g.fillRect(0, 0, getWidth(), getHeight());

    g.dispose();
    bs.show();
}

I want to give my rectangle a color using RGB values like (200, 200, 200) for example; that'll be like a gray.

例如,我想使用 RGB 值(如 (200, 200, 200))为我的矩形指定颜色;那会像灰色。

采纳答案by Loic P.

You can get a Color instance with the simple code:

您可以使用简单的代码获取 Color 实例:

Color myWhite = new Color(255, 255, 255); // Color white

Then, you can set RGB color to your object with something like that:

然后,您可以使用以下内容为您的对象设置 RGB 颜色:

g.setColor(myWhite);

Hope it helps you!

希望对你有帮助!

回答by Atomix

Or you can do:

或者你可以这样做:

setColor(new Color(r, g, b));

For example:

例如:

setColor(new Color(0, 0, 0)); //sets the color to Black

回答by Julio Fernandez

You can do it with Graphics.setColor

你可以用 Graphics.setColor

For example:

例如:

g.setColor(Color.getHSBColor(255, 79, 18));