JavaFX - 旋轉變換



在旋轉中,我們將物件圍繞其原點旋轉特定的角度θ (theta)。從下圖可以看出,點 P(X, Y)位於距原點距離為r的水平 X 座標的角度 φ處。

Rotation

示例

下面的程式演示了 JavaFX 中的旋轉變換。在這裡,我們在相同位置建立了兩個矩形節點,它們具有相同的尺寸,但顏色不同(Blurywood 和藍色)。我們還對 Blurywood 顏色的矩形應用旋轉變換。

將此程式碼儲存在名為RotationExample.java的檔案中。

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.scene.transform.Rotate; 
import javafx.stage.Stage; 
         
public class RotationExample extends Application { 
   @Override 
   public void start(Stage stage) { 
      //Drawing Rectangle1 
      Rectangle rectangle1 = new Rectangle(150, 75, 200, 150); 
      rectangle1.setFill(Color.BLUE); 
      rectangle1.setStroke(Color.BLACK);  
      
      //Drawing Rectangle2 
      Rectangle rectangle2 = new Rectangle(150, 75, 200, 150); 
      
      //Setting the color of the rectangle 
      rectangle2.setFill(Color.BURLYWOOD); 
      
      //Setting the stroke color of the rectangle 
      rectangle2.setStroke(Color.BLACK); 
       
      //creating the rotation transformation 
      Rotate rotate = new Rotate(); 
      
      //Setting the angle for the rotation 
      rotate.setAngle(20); 
      
      //Setting pivot points for the rotation 
      rotate.setPivotX(150); 
      rotate.setPivotY(225); 
        
      //Adding the transformation to rectangle2 
      rectangle2.getTransforms().addAll(rotate); 
        
      //Creating a Group object
      Group root = new Group(rectangle1, rectangle2); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Rotation transformation 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 RotationExample.java 
java RotationExample

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

Rotation Transformation
javafx_transformations.htm
廣告
© . All rights reserved.