如何在 JavaFX 中給文字節點新增模糊效果?


你可以使用 setEffect() 方法給 JavaFX 的任何節點物件新增效果。此方法接受 Effect  類的一個物件,並將其新增到當前節點。

javafx.scene.effect.GaussianBlur.GaussianBlur 類代表模糊效果,其在內部使用高斯卷積核。因此,要給文字節點新增模糊效果,可以:

  • 例項化 Text 類,從建構函式傳遞基本 x、y 座標(位置)和文字字串作為引數。

  • 設定所需的屬性,如字型、筆觸等。

  • 透過例項化 GaussianBlur  類建立模糊效果。

  • 使用 setEffect() 方法給文字節點設定建立的效果。

  • 最後,將建立的文字節點新增到 Group 物件。

示例

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class TextBlurEffect extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      String str = "Welcome to Tutorialspoint";
      Text text = new Text(30.0, 80.0, str);
      //Setting the font
      Font font = Font.font("Brush Script MT", FontWeight.BOLD,
      FontPosture.REGULAR, 65);
      text.setFont(font);
      //Setting the color of the text
      text.setFill(Color.BROWN);
      //Setting the width and color of the stroke
      text.setStrokeWidth(2);
      text.setStroke(Color.BLUE);
      //Setting the blur effect to the text
      GaussianBlur blur = new GaussianBlur();
      text.setEffect(blur);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Blur Effect");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新日期:2020 年 4 月 13 日

425 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.