Search code examples
javafx

Why is the origin shifting after scaling?


I have this simple JavaFX example:

package pkg;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class SimpleScalingExample extends Application {

    @Override
    public void start(Stage stage) {
        Pane p = getPane();
        Pane root = new Pane(p);
        
        Scene scene = new Scene(root, 720, 540);

        stage.setScene(scene);
        stage.setTitle("Example");
        stage.show();
    }

    public Pane getPane() {
        Pane pane = new Pane();

        double width = 100;
        double height = 100;
        pane.setPrefSize(width, height);
        pane.setStyle("-fx-border-color: black; -fx-border-width: 5;");
        // pane.setScaleX(.5);
        // pane.setScaleY(.8);

        Line line1 = new Line(0, 0, width, height);
        line1.setStroke(Color.RED);
        line1.setStrokeWidth(5);

        Line line2 = new Line(0, height, width, 0);
        line2.setStroke(Color.BLUE);
        line2.setStrokeWidth(5);
        pane.getChildren().addAll(line1, line2);

        return pane;
    }
}

When run as is, I get something like this:

Original box

If I uncomment out the setScale lines:

        pane.setScaleX(.5);
        pane.setScaleY(.8);

I get this:

Scaled Box

Since the origin is the upper left, while the box shape looks fine, why is it not set up in the upper left corner?

Bonus question, why are the lines outside of the border in both of these examples?

(It does the same thing is I just create the scene with the pane and not use the root at all.)

This behavior is not intuitive to me.


Solution

  • From the documentation of Node#scaleXProperty():

    Defines the factor by which coordinates are scaled about the center [emphasis added] of the object along the X axis of this Node. This is used to stretch or shrink the node either manually or by using an animation.

    This scale factor is not included in layoutBounds by default, which makes it ideal for scaling the entire node after all effects and transforms have been taken into account.

    The pivot point about which the scale occurs is the center of the untransformed layoutBounds [emphasis added].

    The pivot point is the point that doesn't move. Since the x-coordinate of the pivot point is not at 0 or width, any change in the horizontal scale means both "ends" have to move (and since it's the center, both ends move equally). That's why you're seeing the origin (top left corner) move. Note the documentation of Node#scaleYProperty() is basically the same.

    If you want to scale using a different pivot point then you need to use a Scale transform and add it to the Node#getTransforms() list. By default, the pivot point of a Scale will be (0, 0) (well, technically (0, 0, 0), but we don't care about the third dimension in this case).

    As for your bonus question:

    Bonus question, why are the lines outside of the border in both of these examples?

    That has to do with the StrokeType of the border. Apparently, the default stroke type of a border, at least for one created via CSS, is INSIDE. From what I can tell, you want a border with a stroke type of CENTERED. However, the corners of the ends of the lines will still be outside the pane's border due to simple geometry. If you really want things to align, consider rounding both the ends of the lines and the corners of the border.


    Example

    Code:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.ToggleButton;
    import javafx.scene.layout.Border;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.BorderStroke;
    import javafx.scene.layout.BorderStrokeStyle;
    import javafx.scene.layout.BorderWidths;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Line;
    import javafx.scene.shape.StrokeLineCap;
    import javafx.scene.shape.StrokeLineJoin;
    import javafx.scene.shape.StrokeType;
    import javafx.scene.transform.Scale;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
      public static void main(String[] args) {
        Application.launch(Main.class);
      }
    
      @Override
      public void start(Stage primaryStage) throws Exception {
        var scale = new Scale();
        var scaleBtn = new ToggleButton("Toggle scale");
        scaleBtn.setOnAction(_ -> {
          scale.setX(scaleBtn.isSelected() ? 0.5 : 1.0);
          scale.setY(scaleBtn.isSelected() ? 0.8 : 1.0);
        });
    
        var root = new BorderPane();
        root.setTop(scaleBtn);
        root.setCenter(createPane(scale, 150, 300));
    
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
      }
    
      private Pane createPane(Scale scale, double width, double height) {
        var pane = new Pane();
        pane.setMinSize(width, height);
        pane.setPrefSize(width, height);
        pane.setMaxSize(width, height);
        pane.getTransforms().add(scale);
        pane.getChildren().addAll(
          createLine(Color.BLUE, 0, 0, width, height),
          createLine(Color.RED, 0, height, width, 0));
    
        // CSS approach
        pane.setStyle(
            """
            -fx-border-color: black;
            -fx-border-width: 5;
            -fx-border-style: solid centered line-join round;
            """);
    
        // programmatic approach
        // pane.setBorder(new Border(new BorderStroke(
        //   Color.BLACK,
        //   new BorderStrokeStyle(
        //     StrokeType.CENTERED,  // strokeType
        //     StrokeLineJoin.ROUND, // lineJoin (ROUND the corners)
        //     null,                 // lineCap
        //     1,                    // miterLimit
        //     0,                    // dashOffset
        //     null),                // dashArray
        //   null,
        //   new BorderWidths(5))));
      
        return pane;
      }
    
      private Line createLine(Color stroke, double startX, double startY, double endX, double endY) {
        var line = new Line(startX, startY, endX, endY);
        line.setStroke(stroke);
        line.setStrokeLineCap(StrokeLineCap.ROUND); // round the ends
        line.setStrokeWidth(5);
        return line;
      }
    }
    

    Output:

    GIF of UI created by above example code.