如何在 JavaFX 中向节点添加图像图案?

javafxobject oriented programmingprogramming更新于 2025/4/14 17:22:17

您可以使用 setFill()setStroke() 方法将颜色应用于 JavaFX 中的几何形状。setFill() 方法将颜色添加到形状的内部区域,而 setStroke() 方法将颜色应用于节点的边界。

这两种方法都接受 javafx.scene.paint.Paint 类的对象作为参数。它是用于用颜色填充形状和背景的颜色和渐变的基类。

JavaFX 中的 javafx.scene.paint.ImagePattern类是 Paint 的子类,使用它可以用图像填充形状。

将图像模式应用于几何形状 −

  • 通过实例化 Image 类来创建图像。

  • 绕过上面创建的图像,实例化 ImagePattern 类,将其(连同其他值)作为参数传递给构造函数。

  • 使用 setFill() 方法将创建的图像模式设置为形状。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class ImagePatterns extends Application {
   public void start(Stage stage) {
      //Drawing a circle
      Circle circle = new Circle(75.0f, 65.0f, 40.0f );
      //Drawing a Rectangle
      Rectangle rect = new Rectangle(150, 30, 100, 65);
      //Drawing an ellipse
      Ellipse ellipse = new Ellipse(330, 60, 60, 35);
      //Drawing Polygon
      Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
      //Creating the pattern
      Image map = new Image("http://www.tutorialspoint.com/images/tp-logo.gif");
      ImagePattern pattern = new ImagePattern(map, 20, 20, 40, 40, false);
      //Setting the pattern
      circle.setFill(pattern);
      circle.setStrokeWidth(3);
      circle.setStroke(Color.CADETBLUE);
      rect.setFill(pattern);
      rect.setStrokeWidth(3);
      rect.setStroke(Color.CADETBLUE);
      ellipse.setFill(pattern);
      ellipse.setStrokeWidth(3);
      ellipse.setStroke(Color.CADETBLUE);
      poly.setFill(pattern);
      poly.setStrokeWidth(3);
      poly.setStroke(Color.CADETBLUE);
      //Setting the stage
      Group root = new Group(circle, ellipse, rect, poly);
      Scene scene = new Scene(root, 600, 150);
      stage.setTitle("Setting Colors");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出


相关文章