JavaFX - 透視變換



通常,2D 物件是指只能在二維平面上繪製,並且僅用兩個維度進行測量的物件。但是,使用 JavaFX 應用程式,您可以提供 2D 物件的 3D 錯覺。此效果稱為透視變換效果。

透視變換效果將在 Z 軸方向建立透視,使物件看起來可以在 XYZ 平面上測量,而實際上它僅在 XY 平面上測量。此效果提供非仿射變換,其中源物件中直線的直線度在輸出物件中得以保留。但是,平行性會丟失;與仿射變換不同。

仿射變換是一種線性變換,其中點、直線和平行性從源影像到輸出影像都得以保留。

您可以使用 javafx.scene.effect 包中的 PerspectiveTransform 類將此效果應用於 JavaFX 節點。此類具有以下屬性:

  • input - 此效果的輸入。

  • llx - 輸出位置的 x 座標,源的左下角對映到該位置。

  • lly - 輸出位置的 y 座標,源的左下角對映到該位置。

  • lrx - 輸出位置的 x 座標,源的右下角對映到該位置。

  • lry - 輸出位置的 y 座標,源的右下角對映到該位置。

  • ulx - 輸出位置的 x 座標,源的左上角對映到該位置。

  • uly - 輸出位置的 y 座標,源的左上角對映到該位置。

  • urx - 輸出位置的 x 座標,源的右上角對映到該位置。

  • ury - 輸出位置的 y 座標,源的右上角對映到該位置。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.effect.Effect;
import javafx.scene.effect.PerspectiveTransform;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
         
public class PerspectiveTransformExample extends Application { 
   @Override 
   public void start(Stage stage) {
      PerspectiveTransform prst = new PerspectiveTransform();
      prst.setUlx(10.0);
      prst.setUly(10.0);
      prst.setUrx(310.0);
      prst.setUry(40.0);
      prst.setLrx(310.0);
      prst.setLry(60.0);
      prst.setLlx(10.0);
      prst.setLly(90.0);

      Group g = new Group();
      g.setEffect(prst);
      g.setCache(true);

      Rectangle rect = new Rectangle();
      rect.setX(10.0);
      rect.setY(10.0);
      rect.setWidth(280.0);
      rect.setHeight(80.0);
      rect.setFill(Color.BLUE);

      Text text = new Text();
      text.setX(20.0);
      text.setY(65.0);
      text.setText("JavaFX App");
      text.setFill(Color.WHITE);
      text.setFont(Font.font(null, FontWeight.BOLD, 36));

      g.getChildren().addAll(rect, text);
	  
	  //Creating a Group object  
      Group root = new Group(g); 
               
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Perspective Transform Effect"); 
         
      //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 PerspectiveTransformExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls PerspectiveTransformExample     

輸出

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

PerspectiveTransform_effect_example
廣告

© . All rights reserved.