當我將滑鼠懸停在影像上時,我在影像的某些像素中得到了錯誤的顏色值,這似乎是一種像素偏移。
我在ImageView上使用MouseMoved事件來獲取影像上游標的 x 和 y坐標,然后使用這些坐標中的顏色創建一個Color實體。最后,我使用該顏色填充圓形節點。
我想知道為什么它為某些像素回傳錯誤的顏色值。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);
});
}
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>
這是它的樣子:

uj5u.com熱心網友回復:
您正在通過 fxml 顯式設定 fitwidth / fitheight,因此如果影像尺寸不等于手動設定的適合寬度和高度,則顯示解析度可能與原始影像解析度不同。
您需要做的是將滑鼠位置 x 和 y 從 [0...displayWidth] 和 [0...displayHeight] 的顯示范圍相應地轉換為原始尺寸 [0...originalWidth] [0...原始高度]。
現在棘手的部分是,當您使用 preserveRatio 時,會計算顯示尺寸并且并不總是等于適合的寬度和高度,
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.util.Objects;
public class ColorPickerApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Circle swatch = new Circle(30);
ImageView imageView =
new ImageView(
new Image(
Objects.requireNonNull(
ColorPickerApp.class.getResource(
"Dragon-icon.png"
)
).toExternalForm()
)
);
imageView.setPickOnBounds(true);
imageView.setOnMouseMoved(event -> {
int xPosition = (int) event.getX();
int yPosition = (int) event.getY();
Color pixelColor = imageView.getImage().getPixelReader().getColor(xPosition, yPosition);
swatch.setFill(pixelColor);
System.out.println(pixelColor);
});
VBox layout = new VBox(10, swatch, imageView);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) {
Application.launch();
}
}
示例中的龍影像 Dragon-icon.png:

我將pickOnBounds設定為true,這樣當滑鼠懸停時,影像的透明部分將注冊為顏色變化。
如果你真的快速移動滑鼠,結果可能不準確,因為滑鼠資訊的輪詢不是立即的,但是如果你慢慢移動滑鼠,它應該可以正常作業,至少從我的測驗來看。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/512429.html
標籤:爪哇图片javafx颜色
