JavaFX - 反射效果



反射在科學上被定義為當光線照射到表面(稱為反射面,如鏡子)時發生的一種現象,光線會被反射回來。在這種情況下,這些光波路徑上的所有物體也會被投影回作為影像。您也可以在 JavaFX 應用程式中應用此反射效果。

在 JavaFX 中對節點應用反射效果時,會在節點底部新增其反射。

名為Reflection的類,位於javafx.scene.effect包中,表示反射效果。此類包含四個屬性,它們是:

  • topOpacity - 此屬性為雙精度型別,表示反射頂部邊緣的不透明度值。

  • bottomOpacity - 此屬性為雙精度型別,表示反射底部邊緣的不透明度值。

  • input - 此屬性為 Effect 型別,表示反射效果的輸入。

  • topOffset - 此屬性為雙精度型別,表示輸入底部和反射頂部之間的距離。

  • fraction - 此屬性為雙精度型別,表示輸出中可見的輸入部分。fraction 值的範圍是 0.0 到 1.0。

示例

以下程式是一個演示反射效果的示例。在這裡,我們繪製了文字“Welcome to Tutorialspoint”,並填充了 DARKSEAGREEN 顏色,並對其應用了反射效果。

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

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.effect.Reflection; 
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 ReflectionEffectExample extends Application { 
   @Override 
   public void start(Stage stage) {       
      //Creating a Text object 
      Text text = new Text();       
      
      //Setting font to the text 
      text.setFont(Font.font(null, FontWeight.BOLD, 40));       
      
      //setting the position of the text 
      text.setX(60); 
      text.setY(150); 
      
      //Setting the text to be embedded. 
      text.setText("Welcome to Tutorialspoint");       
      
      //Setting the color of the text 
      text.setFill(Color.DARKSEAGREEN);  
       
      //Instanting the reflection class 
      Reflection reflection = new Reflection(); 
      
      //setting the bottom opacity of the reflection 
      reflection.setBottomOpacity(0.0); 
      
      //setting the top opacity of the reflection 
      reflection.setTopOpacity(0.5); 
      
      //setting the top offset of the reflection 
      reflection.setTopOffset(0.0);
      
      //Setting the fraction of the reflection 
      reflection.setFraction(0.7); 
       
      //Applying reflection effect to the text 
      text.setEffect(reflection);          
         
      //Creating a Group object  
      Group root = new Group(text);   
               
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Reflection effect 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 ReflectionEffectExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls ReflectionEffectExample   

輸出

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

Reflection Effect
廣告