2015-05-24 37 views
0

我正在讀的示例代碼是通過用λ表達式調用它增加一個10像素寬的灰色幀替換上的圖像的邊界處的像素:困惑lambda表達式

public static Image transform(Image in, ColorTransformer t) { 
    int width = (int) in.getWidth(); 
    int height = (int) in.getHeight(); 
    WritableImage out = new WritableImage(width, height); 
    for (int x = 0; x < width; x++) { 
     for (int y = 0; y < height; y++) { 
      out.getPixelWriter().setColor(x, y, 
        t.apply(x, y, in.getPixelReader().getColor(x, y))); 
     } 
    } 
    return out; 
} 

@Override 
public void start(Stage stage) throws Exception { 
    Image image = new Image("test_a.png"); 
    Image newImage = transform(
         image, 
         (x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 || 
            y <= 10 || y >= image.getHeight() - 10) 
            ? Color.WHITE : c 
        ); 
     stage.setScene(new Scene(new VBox(
    new ImageView(image), 
    new ImageView(newImage)))); 
    stage.show(); 
    stage.show(); 
} 
} 

@FunctionalInterface 
interface ColorTransformer { 
    Color apply(int x, int y, Color colorAtXY); 
} 

我困惑的lambda表達式:

Image newImage = transform(
        image, 
        (x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 || 
           y <= 10 || y >= image.getHeight() - 10) 
           ? Color.WHITE : c 
       ); 
  1. 要將框架添加到的人物,我覺得「& &」應該比「||」更加合理。但是,「& &」在這裏不起作用!任何人都可以解釋一下嗎?

  2. 我不太明白「?Color.WHITE:c」。首先,他們爲什麼不在以前的支架?其次,問號(?)是什麼意思?

感謝您提前給予的幫助。

+3

你的問題/問題不在於拉姆達但與邏輯[條件運算符(http://stackoverflow.com /一個/1393766分之17470669)。 – Pshemo

+0

謝謝〜我學到了一些東西。 :-) – SuperDelta

回答

1

首先,您的問題與lambda無關,但表達方式一般。

與第二部分開始:一個?:ç的意思是「如果一個被認爲是真實的,我的價值是否則Ç A類if語句裏面。

至於第一部分:如果個別測試的任何爲真(其中每一個的形式爲點太左/右/上/下),那麼點(大概)在外面,並且是白色的;否則,請使用顏色c。例如,你不能讓它們全部都是真實的:一個觀點不能太過左和太正確。

+0

非常感謝您的評論。我清楚這一點。只有一個問題:代碼根本沒有定義「c」,因此,如果條件爲FALSE,系統將如何獲得「c」的值? – SuperDelta

+0

*是*關於'lambda'的問題; '(x,y,c)'是你的'lambda'的參數列表,所以'c','x'和'y'從調用這個匿名函數獲得它們的值。 –

0

你的程序是相同的:(如果你不使用拉姆達)

public static Image transform(Image in) { 
    int width = (int) in.getWidth(); 
    int height = (int) in.getHeight(); 
    WritableImage out = new WritableImage(width, height); 
    for (int x = 0; x < width; x++) { 
     for (int y = 0; y < height; y++) { 
      Color c = in.getPixelReader().getColor(x, y); 
      if (x <= 10 || x >= image.getWidth() - 10 || 
       y <= 10 || y >= image.getHeight() - 10) 
       c = Color.WHITE; 
      /* else 
       c = c; */ 
      out.getPixelWriter().setColor(x, y, c); 
     } 
    } 
    return out; 
}