如何向 JavaFX 中的節點應用線性漸變(顏色)?
在 JavaFX 中,可以使用 setFill() 方法給形狀新增顏色,為幾何形狀或背景內部新增顏色。
此方法將 javafx.scene.paint.Paint 類的物件作為引數。它是用於填充形狀和背景顏色的顏色和漸變的基礎類。
JavaFX 中的 javafx.scene.paint.LinearGradient 類是 Paint 的子類,可以使用它用圓形線性漸變圖案填充形狀。
要向幾何形狀應用徑向漸變圖案:
傳遞所需引數,例項化 LinearGradient 類。
使用 setFill() 方法將建立的漸變設定到形狀中。
示例
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
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 LinearGradientExample 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 );
//Setting the linear gradient
Stop[] stops = new Stop[] {
new Stop(0, Color.DARKSLATEBLUE),
new Stop(1, Color.DARKRED)
};
LinearGradient gradient =
new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
//Setting the pattern
circle.setFill(gradient);
circle.setStrokeWidth(3);
circle.setStroke(Color.CADETBLUE);
rect.setFill(gradient);
rect.setStrokeWidth(3);
rect.setStroke(Color.CADETBLUE);
ellipse.setFill(gradient);
ellipse.setStrokeWidth(3);
ellipse.setStroke(Color.CADETBLUE);
poly.setFill(gradient);
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("Linear Gradient");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}輸出

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP