-2

Is there a way to get the pixel color / alpha transparency of a pixel of a JavaFX Parent or Scene?

For example, how do I get the pixel color of a StackPane at (x,y)?

In Java Swing there is a method, printAll, from which the pixel can be extracted from any component.

However I can't find such a method in JavaFX.

EDIT: @kleopatra asked for a complete reproductive example, so here is it:

package helloworld;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class HelloWorld extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

How do I get the pixel color of root, say, at x,y?

Guillaume F.
  • 1,010
  • 7
  • 21

1 Answers1

-1

Here is a function to return the pixel color at any x,y coordinate of a node:

static Color getColor(int x, int y, Node node) {
    SnapshotParameters sp = new SnapshotParameters();
    sp.setTransform(new Translate(-x, -y));
    sp.setViewport(new Rectangle2D(0,0,1,1));
    sp.setFill(javafx.scene.paint.Color.TRANSPARENT);
    WritableImage image = node.snapshot(sp, null);
    return image.getPixelReader().getColor(0, 0);
}

It will also work if Node is replaced by Scene, as both classes share the method snapshot.

Guillaume F.
  • 1,010
  • 7
  • 21