2016-12-01 174 views
1

正如你在這裏看到的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); 
     } 
    } 

回答

1

調色板你的鏈接看到的是一個HSV(色調,飽和度,值)顏色調色板。嘗試使用RGB(紅,綠,藍)重現它會導致一些頭痛。

例HSV執行情況(未經測試):

int h = 0; 
for(int x = 0; x < 10; x++) { 
    for(int y = 0; y < 10; y++) { 
     int s = 10 * y; 
     int b = 10 * x; 

     Label label = new Label(); 
     label.setPrefSize(30,30); 
     label.setStyle("-fx-background-color: hsb(" + h + "," + s + "%," + b + "%)"); 
     colorPane.add(label, x,y); 
    } 
} 

注意Java調用它HSB(色調,飽和度,亮度),而不是HSV出於某種原因(可能是因爲「價值」是極其非描述) 。查看Javadoc(查看靜態hsb(double h, double s, double b)方法)以獲取代碼內引用,並使用CSS guide定義CSS(就像我們在這裏所做的那樣)。

1

注意我建議使用Rectangle s而不是Label s。

此外HSB值似乎是更合適:

  • 每列具有相同的色調
  • 一列的前半部分的亮度增加,但飽和保持爲1
  • 第二半列的亮度保持在1,但飽和度從1減小到0

最後一列是一個例外,因爲它只顯示漸變色的灰度g亮度。

下面的代碼允許您創建調色板(或至少充分接近):

@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(); 
} 
相關問題