RotateTransition around a pivot?

前端 未结 2 893
醉酒成梦
醉酒成梦 2021-01-07 08:56

I am using RotateTransiton to rotate a line, but it seems to rotate through center of the line. I would like to rotate it with pivot as one end of the line. Ho

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 09:01

    (on JavaFX 2.2 and JavaFX 8) The best way in my opinion is tranlating the layoutBounds of the node (which contains the pivot point) and translating the node itself the opposite way.

    An example:

    public class Main extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            Group root = new Group();
            primaryStage.setScene(new Scene(root, 140, 140));
    
            Rectangle rect = new Rectangle(1, 1, 40, 40);
    
            // comment movePivot to get the default rotation
            movePivot(rect, -20, -20);
    
            RotateTransition rt = new RotateTransition(Duration.seconds(4),rect);
            rt.setToAngle(720);
            rt.setCycleCount(Timeline.INDEFINITE);
                rt.setAutoReverse(true);
            rt.play();
    
            primaryStage.show();
        }
    
        // this is the function you want
        private void movePivot(Node node, double x, double y){
            node.getTransforms().add(new Translate(-x,-y));
            node.setTranslateX(x); node.setTranslateY(y);
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

提交回复
热议问题