JavaFX - 圖片輸入特效



JavaFX 中的圖片輸入特效只是將圖片嵌入到 JavaFX 螢幕中。就像顏色輸入特效一樣,它用於將指定的彩色矩形區域作為輸入傳遞給另一個特效。圖片輸入特效用於將指定的圖片作為輸入傳遞給另一個特效。

應用此特效後,指定的圖片不會被修改。此特效可應用於任何節點。

名為 `ImageInput` 的類(位於 `javafx.scene.effect` 包中)表示圖片輸入特效,此類包含三個屬性,它們是:

  • x - 此屬性為 Double 型別;它表示源圖片位置的 x 座標。

  • y - 此屬性為 Double 型別;它表示源圖片位置的 y 座標。

  • source - 此屬性為 Image 型別;它表示用作此特效源的圖片。(作為輸入傳遞)

示例

以下程式是一個演示圖片輸入特效的示例。在這裡,我們在位置 150, 100 建立一個圖片輸入,並使用以下圖片(Tutorialspoint 徽標)作為此特效的源。

Image Input Effect

我們建立一個矩形並將其應用於此特效。將此程式碼儲存在名為 `ImageInputEffectExample.java` 的檔案中。

import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.effect.ImageInput; 
import javafx.scene.image.Image; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 
         
public class ImageInputEffectExample extends Application { 
   @Override  
   public void start(Stage stage) {       
      //Creating an image 
      Image image = new Image("https://tutorialspoint.tw/green/images/logo.png"); 
             
      //Instantiating the Rectangle class 
      Rectangle rectangle = new Rectangle(); 
     
      //Instantiating the ImageInput class 
      ImageInput imageInput = new ImageInput(); 
      
      //Setting the position of the image
      imageInput.setX(150); 
      imageInput.setY(100);       
      
      //Setting source for image input  
      imageInput.setSource(image); 
       
      //Applying image input effect to the rectangle node 
      rectangle.setEffect(imageInput);    
         
      //Creating a Group object  
      Group root = new Group(rectangle);   
               
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Sample Application"); 
         
      //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 ImageInputEffectExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls ImageInputEffectExample  

輸出

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

Image Input Effect Example
廣告