gpt4 book ai didi

java - 调色板算法输出从红色到蓝色的颜色网格

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:02 25 4
gpt4 key购买 nike

如你所见http://www.rapidtables.com/web/color/RGB_Color.htm颜色按照算法模式从红色变为蓝色,从深色变为白色。您将如何在基本循环中编写代码?我正在为 JavaFX 培训做这个!

这是我目前使用随机颜色的基本结构,应该用算法代替:

    for(int x = 0;x<12;x++) {
for(int y = 0; y< 10; y++) {
Random random = new Random();
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);

Label label = new Label();
label.setPrefSize(30,30);
label.setStyle("-fx-background-color: rgb(" + r + "," + g + "," + b + ")");
colorPane.add(label, x,y);
}
}

最佳答案

请注意,我建议使用 Rectangle 而不是 Label

另外 hsb 值似乎更合适:

  • 每一列都有相同的色调
  • 前半列亮度增加,但饱和度保持在1
  • 该列的后半部分亮度保持为 1,但饱和度从 1 降低到 0

最后一列是个异常(exception),因为它只显示亮度增加的灰度。

以下代码允许您创建调色板(或至少足够接近):

@Override
public void start(Stage primaryStage) {
GridPane gridPane = new GridPane();
gridPane.setHgap(4);
gridPane.setVgap(4);

final int columns = 12;
final int rows = 10;
final int fullBrightness = (rows - 1) / 2;
final int columnCount = columns - 1;

// fill upper half with full saturation but increasing brightness
for (int y = 0; y <= fullBrightness; y++) {
double brightness = y / (double) fullBrightness;
for (int x = 0; x < columnCount; x++) {
Rectangle rect = new Rectangle(15, 15, Color.hsb(x * (360d / (columns - 1)), 1, brightness));
rect.setStroke(Color.BLACK);
gridPane.add(rect, x, y);
}
}

// fill lower half with full brightness but decreasing saturation
for (int y = fullBrightness + 1; y < rows; y++) {
double saturation = 1 - ((double) (y - fullBrightness)) / (columns - 1 - fullBrightness);
for (int x = 0; x < columnCount; x++) {
Rectangle rect = new Rectangle(15, 15, Color.hsb(x * (360d / (columns - 1)), saturation, 1));
rect.setStroke(Color.BLACK);
gridPane.add(rect, x, y);
}
}

// fill last column with grayscale
for (int y = 0, maxIndex = rows - 1; y < rows; y++) {
Rectangle rect = new Rectangle(15, 15, Color.hsb(0, 0, y / (double) maxIndex));
rect.setStroke(Color.BLACK);
gridPane.add(rect, columnCount, y);
}

Scene scene = new Scene(gridPane);

primaryStage.setScene(scene);
primaryStage.show();
}

关于java - 调色板算法输出从红色到蓝色的颜色网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40914300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com