Reputation: 253
I am reading an example code which is to add a 10 pixel wide gray frame replacing the pixels on the border of an image by calling it with the lambda expression:
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);
}
I am confused about the lambda expression:
Image newImage = transform(
image,
(x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 ||
y <= 10 || y >= image.getHeight() - 10)
? Color.WHITE : c
);
To add a frame to a figure, I think "&&" should be more reasonable than "||". But, "&&" does not work here! Could anyone please explain this?
I do not really understand "? Color.WHITE : c". Firstly, why are they outside the previous bracket? Secondly, what does the question mark(?) mean?
Thank you for your help in advance.
Upvotes: 0
Views: 99
Reputation:
Your program is equivalent to this: (if you don't use lambda)
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;
}
Upvotes: 0
Reputation: 49805
First off, your question has nothing to do with lambda
, but expressions in general.
Starting with the second part: A ?
B :
C means "if A is considered true, my value is B otherwise it is C. A kind of if
statement inside of an expression.
As to the first part: if any of the individual tests is true (each of which is of the form the point is too far left/right/up/down), then the point is (presumably) outside, and is colored white; otherwise, use the color c
. You can't have them all be true at once: a point can't both be too far left and too far right, for example.
Upvotes: 1