简体   繁体   English

JavaFX:如何获得一个像素的颜色和透明度?

[英]JavaFX: how to get the color and alpha transparency of a pixel?

Is there a way to get the pixel color / alpha transparency of a pixel of a JavaFX Parent or Scene ?有没有办法获得 JavaFX ParentScene像素的像素颜色/alpha 透明度?

For example, how do I get the pixel color of a StackPane at (x,y) ?例如,如何在(x,y)处获取StackPane的像素颜色?

In Java Swing there is a method , printAll , from which the pixel can be extracted from any component.Java Swing 中有一个方法printAll ,可以从任何组件中提取像素。

However I can't find such a method in JavaFX.但是我在 JavaFX 中找不到这样的方法。

EDIT: @kleopatra asked for a complete reproductive example, so here is it:编辑:@kleopatra 要求提供一个完整的生殖示例,所以这里是:

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 ?如何获得root的像素颜色,例如x,y

Here is a function to return the pixel color at any x,y coordinate of a node :这是一个 function 返回node任意x,y坐标处的像素颜色:

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 .如果NodeScene替换,它也可以工作,因为两个类共享方法snapshot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM