【发布时间】:2015-05-24 16:20:30
【问题描述】:
我正在阅读一个示例代码,该代码是添加一个 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
);
给图形加边框,我觉得“&&”应该比“||”更合理。但是,“&&”在这里不起作用!谁能解释一下?
我不太明白“?Color.WHITE : c”。首先,为什么它们在前一个括号之外?其次,问号(?)是什么意思?
提前感谢您的帮助。
【问题讨论】:
-
您的问题/问题不在于 lambda,而在于 conditional operator 的逻辑。
-
谢谢~我学到了一些东西。 :-)
标签: java