将鼠标悬停在 javafx 中的图像节点上时无法获得正确的颜色

Min*_*Brc 3 java javafx image colors

当我将鼠标悬停在图像上我在图像的某些像素中得到了错误的颜色值,这似乎是一种像素移位。

我在ImageView上使用MouseMoved事件来获取图像上光标的x 和 y坐标,然后使用这些坐标中的颜色创建一个Color实例。最后,我使用该颜色填充 Circle 节点。

我想知道为什么它返回某些像素的错误颜色值。

PS:我在 png 和 jpeg 图像上尝试过,但同样的事情发生了。

这是控制器的初始化方法,我将事件侦听器设置为ImageView

 @FXML
    public ImageView inputImage;

    public void initialize() {

        inputImage.setOnMouseMoved(event -> {
            int xPosition = (int) event.getX();
            int yPosition = (int) event.getY();

            Color pixelColor = inputImage.getImage().getPixelReader().getColor(xPosition, yPosition);

            circleColor.setFill(pixelColor);
        });
    }
Run Code Online (Sandbox Code Playgroud)

FXML文件的一部分:

            <VBox HBox.hgrow="ALWAYS" alignment="CENTER">
                <HBox alignment="CENTER">
                    <VBox.margin>
                        <Insets bottom="50.0"/>
                    </VBox.margin>

                    <ImageView fx:id="inputImage" pickOnBounds="true" preserveRatio="true" fitHeight="300"
                               fitWidth="300">
                        <Image url="@../Resources/Default-image.png" backgroundLoading="true"/>
                    </ImageView>
                </HBox>

                <HBox alignment="CENTER">
                    <Button onAction="#handleFileChooserClick" text="load image"/>
                </HBox>
            </VBox>

            <VBox prefWidth="200" alignment="TOP_CENTER">
                <padding>
                    <Insets top="60" bottom="60"/>
                </padding>

                <VBox alignment="TOP_CENTER">
                    <Circle radius="70" fill="orange" stroke="black" fx:id="circleColor"/>
                    <VBox.margin>
                        <Insets bottom="50.0"/>
                    </VBox.margin>
                </VBox>

                <Button textAlignment="CENTER" text="Isolate Color"/>
            </VBox>
Run Code Online (Sandbox Code Playgroud)

它看起来像这样: 在此输入图像描述

zin*_*yar 6

您通过 fxml 显式设置 fitwidth / fitheight,因此如果图像尺寸不等于手动设置的适合宽度和高度,则显示分辨率可能与原始图像分辨率不同。

您需要做的是将鼠标位置 x 和 y 相应地从 [0...displayWidth] 和 [0...displayHeight] 的显示范围转换为原始尺寸 [0...originalWidth] [0...原始高度]。

现在棘手的部分是,当您使用preserveRatio时,显示尺寸会被计算出来,并且并不总是等于适合的宽度和高度,这个答案描述了一种使用保留比率获取imageView的显示宽度和高度的方法。

现在您已经有了显示尺寸和原始尺寸,您可以计算一个新的对 (x, y) :

int adjustedX = mouseX * originalWidth / displayWidth;
int adjustedY = mouseY * originalHeight / displayHeight;
Run Code Online (Sandbox Code Playgroud)

您可以使用它们从输入图像中获取颜色。