0

我正在尝试在 JavaFX 中制作一个测量工具以在 ImageView 上使用,在这里我单击图像中的两个点,然后获取它们之间的距离 - 我已经弄清楚了这部分。但是,我也希望能够查看/标记我点击的图像上的位置,但我无法想象如何最好地做到这一点。我将附上测量工具的代码,以便您更好地了解我正在处理的内容。我认为它必须在第一个 if 循环内,我可以在 (secondposx, secondposy) 处设置标记 - 但我的问题是,我怎样才能做出那个标记?你有什么好主意吗?:-)

private void btnMeasureAction(ActionEvent event) {
    if (btnMeasure.isSelected()) {
        imgView.setCursor(Cursor.CROSSHAIR);
        imgView.setPickOnBounds(true);
        imgView.setOnMouseClicked(e -> {
            secondposx = e.getX();
            secondposy = e.getY();
// I think the MARK should be set here.
                //System.out.println(secondposx + ", " + secondposy);


            if ((firstposx == 0)) {
                firstposx = secondposx;
                firstposy = secondposy;
                //System.out.println(firstposx + ", " + firstposy);
            } else {
                double distance = Math.sqrt(Math.pow((secondposx - firstposx), 2) + Math.pow((secondposy - firstposy), 2));
                System.out.println("The distance is: " + distance);
                btnMeasure.setSelected(false);
                imgView.setOnMouseClicked(null);
                imgView.setCursor(Cursor.DEFAULT);
                firstposx = 0;
                firstposy = 0;
                secondposy = 0;
                secondposx = 0;
            }
4

2 回答 2

2

一种解决方案是将您的图像视图包装PanePane. 即代替

scrollPane.setContent(imgView);

Pane imgContainer = new Pane(imgView);
scrollPane.setContent(imgContainer);

然后做

Circle marker = new Circle(secondposx, secondposy, 2, Color.SALMON);
imgContainer.getChildren().add(marker);

如果您想将标记直接添加到现有的AnchorPane(或作为图像视图的祖先的任何其他容器),并避免创建额外的容器,您可以这样做,但您需要将图像视图的坐标更改为那个容器。您可以先获取场景中的坐标,然后将场景坐标更改为容器坐标:

Point2D sceneCoords = new Point2D(e.getSceneX(), e.getSceneY());
Point2D anchorPaneCoords = anchorPane.sceneToLocal(sceneCoords);
Circle marker = new Circle(anchorPaneCoords.getX(), anchorPaneCoords.getY(), 2, Color.CORAL);
anchorPane.getChildren().add(marker);
于 2017-05-04T14:42:21.417 回答
1

试试这个 :

Circle c = new Circle(secondposx, secondposy, 5, Color.RED);
anchorPane.getChildren().add(c);

然后,如果你想删除它:

anchorPane.getChildren().remove(c);

是的,在这个地方

于 2017-05-04T14:32:16.980 回答