将旋转的ImageView装入应用程序窗口/场景

时间:2018-11-01 21:45:28

标签: javafx rotation imageview translate

在JavaFX中,我试图在“应用程序”窗口中显示旋转的ImageView。 因此,我将其放到stackPane中以使其始终居中,并且将ImageView和stackPane的宽度/高度绑定到场景的宽度/高度,以使其尽可能大。

图像不旋转后,此方法即可正常工作。
只要使用stackPane.setRotate(90)将Image旋转90°(并交换绑定的宽度/高度),然后stackPane就不再绑定到“应用程序窗口”(或场景)的左上角。

如何正确放置旋转的图像?

在示例代码中,[任何键]都会将旋转角度切换为90°/ 0°,这样旋转图像的位置问题就变得可见了:

public class RotationTest extends Application {

  boolean rotated = false;

  public static void main(String[] args) {
    Application.launch(args);
  }

  @Override
  public void start(Stage primaryStage) {
    primaryStage.setTitle("Rotation test");

    Group root = new Group();
    Scene scene = new Scene(root, 1024,768);

    //a stackPane is used to center the image
    StackPane stackPane = new StackPane();
    stackPane.setStyle("-fx-background-color: black;");

    stackPane.prefHeightProperty().bind(scene.heightProperty());
    stackPane.prefWidthProperty().bind(scene.widthProperty());

    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
      public void handle(KeyEvent event) {
        //toggle rotate 90° / no rotation
        rotated = !rotated;

        stackPane.prefHeightProperty().unbind();
        stackPane.prefWidthProperty().unbind();

        if (rotated){
          stackPane.setRotate(90);
          //rotation: exchange width and height for binding to scene
          stackPane.prefWidthProperty().bind(scene.heightProperty());
          stackPane.prefHeightProperty().bind(scene.widthProperty());
        }else{
          stackPane.setRotate(0);
          //no rotation: height is height and width is width
          stackPane.prefHeightProperty().bind(scene.heightProperty());
          stackPane.prefWidthProperty().bind(scene.widthProperty());
        }
      }
    });


    final ImageView imageView = new ImageView("file:D:/test.jpg");
    imageView.setPreserveRatio(true);
    imageView.fitWidthProperty().bind(stackPane.prefWidthProperty());
    imageView.fitHeightProperty().bind(stackPane.prefHeightProperty());

    stackPane.getChildren().add(imageView);

    root.getChildren().add(stackPane);
    primaryStage.setScene(scene);
    primaryStage.show();

  }
}

结果:

Result with no Rotation

不旋转,stackPane(黑色)就可以完美地适合窗口,并且即使使用鼠标调整了窗口的大小,图像也具有正确的大小。

Result with Rotation of stackPane by 90 degree

按下[任意键]后,将旋转stackPane。

stackPane(黑色)似乎具有正确的宽度/高度,并且图像似乎也已正确旋转。但是stackPane不再位于左上角???当用鼠标调整窗口大小时,它会四处移动。

2 个答案:

答案 0 :(得分:1)

为什么不简单地将Group和首选尺寸排除在等式之外?

根会自动调整大小以适合场景,您可以使用其width / height属性来绑定fitWidthfitHeight属性:

private static void setRotated(boolean rotated, ImageView targetNode, Pane parent) {
    double angle;
    if (rotated) {
        angle = 90;
        targetNode.fitWidthProperty().bind(parent.heightProperty());
        targetNode.fitHeightProperty().bind(parent.widthProperty());
    } else {
        angle = 0;
        targetNode.fitWidthProperty().bind(parent.widthProperty());
        targetNode.fitHeightProperty().bind(parent.heightProperty());
    }
    targetNode.setRotate(angle);
}

@Override
public void start(Stage primaryStage) {
    Image image = new Image("file:D:/test.jpg");
    ImageView imageView = new ImageView(image);
    imageView.setPreserveRatio(true);

    StackPane root = new StackPane(imageView);
    root.setStyle("-fx-background-color: black;");

    // initialize unrotated
    setRotated(false, imageView, root);

    Scene scene = new Scene(root, 1024, 768);

    scene.setOnKeyPressed(evt -> {
        // toggle between 0° and 90° rotation
        setRotated(imageView.getRotate() == 0, imageView, root);
    });

    primaryStage.setScene(scene);
    primaryStage.show();
}

请注意,如果放置在其他布局中,这可能不会导致正确的布局,因为尺寸约束可能计算错误。

您可以通过实现自己的区域来解决此问题:

public class CenteredImage extends Region {
    private final BooleanProperty rotated = new SimpleBooleanProperty();
    private final ImageView imageView = new ImageView();

    public CenteredImage() {
        // make sure layout gets invalidated when the image changes
        InvalidationListener listener = o -> requestLayout();
        imageProperty().addListener(listener);
        rotated.addListener((o, oldValue, newValue) -> {
            imageView.setRotate(newValue ? 90 : 0);
            requestLayout();
        });
        getChildren().add(imageView);
        imageView.setPreserveRatio(true);
    }

    public final BooleanProperty rotatedProperty() {
        return rotated;
    }

    public final void setRotated(boolean value) {
        this.rotated.set(value);
    }

    public boolean isRotated() {
        return rotated.get();
    }

    public final void setImage(Image value) {
        imageView.setImage(value);
    }

    public final Image getImage() {
        return imageView.getImage();
    }

    public final ObjectProperty<Image> imageProperty() {
        return imageView.imageProperty();
    }

    @Override
    protected double computeMinWidth(double height) {
        return 0;
    }

    @Override
    protected double computeMinHeight(double width) {
        return 0;
    }

    @Override
    protected double computePrefWidth(double height) {
        Image image = getImage();
        Insets insets = getInsets();

        double add = 0;
        if (image != null && height > 0) {
            height -= insets.getBottom() + insets.getTop();
            add = isRotated()
                    ? height / image.getWidth()  * image.getHeight()
                    : height / image.getHeight()  * image.getWidth();
        }

        return insets.getLeft() + insets.getRight() + add;
    }

    @Override
    protected double computePrefHeight(double width) {
        Image image = getImage();
        Insets insets = getInsets();

        double add = 0;
        if (image != null && width > 0) {
            width -= insets.getLeft() + insets.getRight();
            add = isRotated()
                    ? width / image.getHeight()  * image.getWidth()
                    : width / image.getWidth()  * image.getHeight();
        }

        return insets.getTop() + insets.getBottom() + add;
    }

    @Override
    protected double computeMaxWidth(double height) {
        return Double.MAX_VALUE;
    }

    @Override
    protected double computeMaxHeight(double width) {
        return Double.MAX_VALUE;
    }

    @Override
    protected void layoutChildren() {
        Insets insets = getInsets();
        double left = insets.getLeft();
        double top = insets.getTop();
        double availableWidth = getWidth() - left - insets.getRight();
        double availableHeight = getHeight() - top - insets.getBottom();

        // set fit sizes
        if (isRotated()) {
            imageView.setFitWidth(availableHeight);
            imageView.setFitHeight(availableWidth);
        } else {
            imageView.setFitWidth(availableWidth);
            imageView.setFitHeight(availableHeight);
        }

        // place image
        layoutInArea(imageView, left, top, availableWidth, availableHeight, 0, null, false,
                false, HPos.CENTER, VPos.CENTER);

    }

}
@Override
public void start(Stage primaryStage) {
    Image image = new Image("file:D:/test.jpg");
    ImageView imageView = new ImageView(image);
    imageView.setPreserveRatio(true);

    CenteredImage imageArea = new CenteredImage();
    imageArea.setImage(image);

    imageArea.setStyle("-fx-background-color: black;");

    imageArea.setPrefWidth(300);

    SplitPane splitPane = new SplitPane(new Region(), imageArea);
    SplitPane.setResizableWithParent(imageArea, true);

    Scene scene = new Scene(splitPane, 1024, 768);

    scene.setOnKeyPressed(evt -> {
        // toggle between 0° and 90° rotation
        imageArea.setRotated(!imageArea.isRotated());
    });

    primaryStage.setScene(scene);
    primaryStage.show();
}

答案 1 :(得分:0)

我找到了一个解决方案:-) Fabian的方法启发了我(谢谢!!),我的老朋友Pit帮助我进行了调试(也谢谢!!)

当将resize()应用于旋转的窗格(甚至是节点-我没有尝试过)时,似乎JavaFX的布局定位算法存在问题:

Origin movement following setRotate and resize

按照Fabian的想法,我调试了Pane类的layoutChildren()方法。我发现setRotate()之后的重定位是正确的,并且可以按预期保持子窗格的中心。但是,一旦调用resize()(这样做是因为将旋转后的子窗格再次装入其父窗格,并且总是在用户调整窗口大小时,这样做),原始计算就出错了:

上面的图片以绿色描绘了setRotate(90),resize()和relocate()的序列,并以蓝色描绘了setRotate(270)的序列。在1024x786示例中,一个蓝色/绿色小圆圈描绘了相应的原点及其坐标。

分析

似乎为了计算窗格的大小,resize()并未使用BoundsInParent-Property(请参见Node的JavaFX-Docu)中的高度和宽度,而是使用了getWidth()和getHeight(),它们似乎反映了BoundsInLocal。结果,对于90°或270°的旋转,高度和宽度似乎互换了。因此,当resize()尝试在调整大小后再次将子窗格居中时,新原点的计算误差仅为宽度和高度之差的一半(delta =(width-height)/ 2)。

解决方案

为旋转= 90或270度的窗格调整大小后,需要应用重定位(delta,-delta)。

我的实现的结构遵循Fabian的基本思想:我已经构建了一个布局器RotatablePaneLayouter:Region,该布局器仅覆盖layoutChildren()方法。在其构造函数中,它获得一个Pane(在我的示例中为StackPane),该Pane可以包含任意数量的子级(在我的示例中为ImageView)并且可以旋转。

LayoutChildren()然后只执行子窗格的resize()和relocate()即可将其完全放入RotateablePaneLayouter中,并尊重子窗格的方向。

布局器助手(RotateablePaneLayouter:Region)

public class RotatablePaneLayouter extends Region {
  private Pane child;

  public RotatablePaneLayouter(Pane child) {
    getChildren().add(child);
    this.child = child;

    // make sure layout gets invalidated when the child orientation changes
    child.rotateProperty().addListener(new ChangeListener<Number>() {
      @Override
      public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
        requestLayout();
      }
    });
  }

  @Override
  protected void layoutChildren() {
    // set fit sizes:
    //resize child to fit into RotatablePane and correct movement caused by resizing if necessary
    if ((child.getRotate() == 90)||(child.getRotate() == 270)) {
      //vertical
      child.resize( getHeight(), getWidth() ); //exchange width and height
      // and relocate to correct movement caused by resizing
      double delta = (getWidth() - getHeight()) / 2;
      child.relocate(delta,-delta);
    } else {
      //horizontal
      child.resize( getWidth(), getHeight() ); //keep width and height
      //with 0° or 180° resize does no movement to be corrected
      child.relocate(0,0);
    }
  }
}

要使用它,请执行以下操作:首先将要旋转的窗格放置到布局器中,而不是直接放置窗格。

这里是示例主程序的代码。您可以使用空格键将子窗格旋转90、180、270,然后再旋转0度。您也可以使用鼠标调整窗口大小。布局器始终设法正确放置旋转的窗格。

使用版面工具的示例

public class RotationTest extends Application {
  public static void main(String[] args) {
   Application.launch(args);
  }

  @Override
  public void start(Stage primaryStage) {

    //image in a StackPane to be rotated
    final ImageView imageView = new ImageView("file:D:/Test_org.jpg");
    imageView.setPreserveRatio(true);
    StackPane stackPane = new StackPane(imageView); //a stackPane is used to center the image
    stackPane.setStyle("-fx-background-color: black;");
    imageView.fitWidthProperty().bind(stackPane.widthProperty());
    imageView.fitHeightProperty().bind(stackPane.heightProperty());

    //container for layouting rotated Panes
    RotatablePaneLayouter root = new RotatablePaneLayouter(stackPane);
    root.setStyle("-fx-background-color: blue;");

    Scene scene = new Scene(root, 1024,768);

    scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
      @Override
      public void handle(KeyEvent event) {
        if (event.getCode() == KeyCode.SPACE) {
          //rotate additionally 90°
          stackPane.setRotate((stackPane.getRotate() + 90) % 360);
        }
      }
    });

    primaryStage.setTitle("Rotation test");
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

对我来说,这似乎是resize()中javaFX错误的解决方法。