如何在JavaFX中将图像图案添加到节点?
你可以使用 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("https://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);
}
}输出

广告
数据结构
网络
关系型数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP