JavaFX - 旋轉轉換



JavaFX 中的動畫可以應用於更改物件的幾何形狀、屬性、位置等。旋轉轉換用於透過保留物件的形狀和屬性來處理其位置。

物件在其中心點樞轉並圍繞其旋轉。這種型別的動畫稱為旋轉轉換。各種軟體允許您透過旋轉物件來將其應用於物件,同時顯示該物件。

這種型別的動畫可以在物件進入應用程式或退出應用程式時應用。

JavaFX 中的旋轉轉換

JavaFX 中的旋轉轉換是使用javafx.animation包中的RotateTransition類應用的。這是透過指定轉換的起始值、結束值和持續時間來完成的。RotateTransition 類具有以下屬性:

  • axis - 指定此 RotateTransition 的旋轉軸。

  • node - 此 RotateTransition 的目標節點。

  • byAngle - 指定此 RotateTransition 從起始位置開始遞增的停止角度值。

  • fromAngle - 指定此 RotateTransition 的起始角度值。

  • toAngle - 指定此 RotateTransition 的停止角度值。

  • duration - 此 RotateTransition 的持續時間。

示例

以下是演示 JavaFX 中旋轉轉換的程式。將此程式碼儲存在名為RotateTransitionExample.java的檔案中。

import javafx.animation.RotateTransition; 
import javafx.application.Application; 
import static javafx.application.Application.launch; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Polygon; 
import javafx.stage.Stage; 
import javafx.util.Duration; 
         
public class RotateTransitionExample extends Application { 
   @Override 
   public void start(Stage stage) {      
      //Creating a hexagon 
      Polygon hexagon = new Polygon();        
      
      //Adding coordinates to the hexagon 
      hexagon.getPoints().addAll(new Double[]{        
         200.0, 50.0, 
         400.0, 50.0, 
         450.0, 150.0,          
         400.0, 250.0, 
         200.0, 250.0,                   
         150.0, 150.0, 
      }); 
      //Setting the fill color for the hexagon 
      hexagon.setFill(Color.BLUE); 
       
      //Creating a rotate transition    
      RotateTransition rotateTransition = new RotateTransition(); 
      
      //Setting the duration for the transition 
      rotateTransition.setDuration(Duration.millis(1000)); 
      
      //Setting the node for the transition 
      rotateTransition.setNode(hexagon);       
      
      //Setting the angle of the rotation 
      rotateTransition.setByAngle(360); 
      
      //Setting the cycle count for the transition 
      rotateTransition.setCycleCount(50); 
      
      //Setting auto reverse value to false 
      rotateTransition.setAutoReverse(false); 
      
      //Playing the animation 
      rotateTransition.play(); 
         
      //Creating a Group object   
      Group root = new Group(hexagon); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);   
      
      //Setting title to the Stage 
      stage.setTitle("Rotate transition example "); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   }      
   public static void main(String args[]){ 
      launch(args); 
   } 
} 

使用以下命令從命令提示符編譯並執行儲存的 java 檔案。

javac --module-path %PATH_TO_FX% --add-modules javafx.controls RotateTransitionExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls RotateTransitionExample

輸出

執行後,上述程式將生成如下所示的 JavaFX 視窗。

Rotate Transition
廣告