如何在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.tw/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);
   }
}

輸出

更新於: 2020 年 5 月 16 日

944 次瀏覽

啟動你的職業

完成課程,獲得認證

開始
廣告