【问题标题】:JavaFX: how to get the color and alpha transparency of a pixel?JavaFX:如何获得像素的颜色和 alpha 透明度?
【发布时间】:2020-04-12 03:56:29
【问题描述】:

有没有办法获取 JavaFX ParentScene 的像素的像素颜色/alpha 透明度?

例如,如何在(x,y) 处获取StackPane 的像素颜色?

Java Swing there is a methodprintAll,可以从中提取任意分量的像素。

但是我在 JavaFX 中找不到这样的方法。

编辑:@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();
    }
}

我如何获得root 的像素颜色,比如x,y

【问题讨论】:

标签: java javafx


【解决方案1】:

这是一个函数,用于返回 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);
}

如果将Node 替换为Scene,它也会起作用,因为两个类共享方法snapshot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2013-04-18
    • 2011-04-04
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多