如何在 JavaFX 中为文本节点添加反射效果?


在 JavaFX 中,可以使用 setEffect() 方法为任何节点对象添加效果。该方法接受一个 Effect 类的对象,并将其添加到当前节点中。

反射效果在给定内容的下方渲染其倒影。javafx.scene.effect.Reflection 表示反射效果。若要向文本节点添加模糊效果,请执行以下操作:

  • 通过传入基本 x、y 坐标(位置)和文本字符串作为构造函数的参数来实例化 Text 类。

  • 设置所需的属性,如字体、描边等。

  • 通过实例化 Reflection 类来创建一个模糊效果。

  • 使用 setEffect() 方法将创建的效果设置为文本节点。

  • 最后,将创建的文本节点添加到 Group 对象中。

示例

import java.io.FileNotFoundException;
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.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class ReflectionEffect 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);
      //Creating the reflection effect
      Reflection reflection = new Reflection();
      reflection.setFraction(0.8);
      //Setting the effect to the text
      text.setEffect(reflection);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Reflection Effect");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出

更新于: 2020 年 5 月 16 日

267 次浏览

开启您的 职业生涯

完成该课程,获得认证

开始
广告
© . All rights reserved.