JavaFX - 描邊轉換



我們已經瞭解到,填充轉換用於更改形狀區域的顏色。與此類似,描邊轉換用於更改形狀的描邊顏色。

JavaFX 中的形狀可以包含三種類型的描邊:內部、外部和居中;並應用不同的屬性。此轉換忽略描邊的屬性,而只是在指定持續時間內更改其顏色。

描邊轉換

JavaFX 使用屬於 javafx.animation 包的 StrokeTransition 類提供描邊轉換。透過匯入此類,我們可以更改 JavaFX 應用程式上任何形狀的描邊顏色。要實現此動畫,此類提供了各種屬性 -

  • duration - 此 StrokeTransition 的持續時間。

  • shape - 此 StrokeTransition 的目標形狀。

  • fromValue - 指定此 StrokeTransition 的起始顏色值。

  • toValue - 指定此 StrokeTransition 的結束顏色值。

示例

以下是演示 JavaFX 中 Stoke Transition 的程式。將此程式碼儲存在名為 StrokeTransitionExample.java 的檔案中。

import javafx.animation.StrokeTransition; 
import javafx.application.Application; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Circle; 
import javafx.stage.Stage; 
import javafx.util.Duration; 
         
public class StrokeTransitionExample extends Application { 
   @Override 
   public void start(Stage stage) {      
      //Drawing a Circle 
      Circle circle = new Circle(); 
      
      //Setting the position of the circle 
      circle.setCenterX(300.0f); 
      circle.setCenterY(135.0f); 
      
      //Setting the radius of the circle 
      circle.setRadius(100.0f); 
      
      //Setting the color of the circle 
      circle.setFill(Color.BROWN); 
      
      //Setting the stroke width of the circle 
      circle.setStrokeWidth(20); 
       
      //creating stroke transition  
      StrokeTransition strokeTransition = new StrokeTransition(); 
      
      //Setting the duration of the transition 
      strokeTransition.setDuration(Duration.millis(1000)); 
      
      //Setting the shape for the transition 
      strokeTransition.setShape(circle); 
      
      //Setting the fromValue property of the transition (color) 
      strokeTransition.setFromValue(Color.BLACK); 
      
      //Setting the toValue property of the transition (color) 
      strokeTransition.setToValue(Color.BROWN); 
       
      //Setting the cycle count for the transition 
      strokeTransition.setCycleCount(50); 
      
      //Setting auto reverse value to false 
      strokeTransition.setAutoReverse(false); 
      
      //Playing the animation 
      strokeTransition.play(); 
         
      //Creating a Group object  
      Group root = new Group(circle); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Stroke 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 StrokeTransitionExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls StrokeTransitionExample 

輸出

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

Stroke Transition
廣告