2017-02-15 174 views
2

我有以下問題: 我正在寫一個程序,就像一張空白紙,您可以在其上書寫(自由手寫),插入文本,添加圖像,添加pdf等... 對於我需要將由用戶添加到窗格的節點轉換爲圖像的一個特定功能。值得慶幸的是,JavaFX的節點提供了一個很好的方法:拍攝JavaFX TextArea和WebView的快照

public void snapshot(...) 

但有一個問題:當我試圖讓他們失敗文本的對象的快照。我可以拍攝快照的唯一節點是javafx.scene.text.Text。 以下類故障:

javafx.scene.control.TextArea 
javafx.scene.web.WebView 

下面是一個例子來說明我的問題:通過創建javafx.scene.text.Text-對象周圍的工作

import javafx.application.Application; 
import javafx.stage.Stage; 
import javafx.scene.Scene; 
import javafx.scene.SnapshotParameters; 
import javafx.scene.image.Image; 
import javafx.scene.image.ImageView; 
import javafx.scene.control.TextArea; 
import javafx.scene.layout.Pane; 
import javafx.scene.paint.Color; 
import javafx.scene.text.Text; 

public class Main extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     try { 

      TextArea textArea = new TextArea("Lorem Ipsum is simply dummy text" 
        + " of the printing and typesetting industry. Lorem Ipsum has been \n" 
        + "the industry's standard dummy text ever since the 1500s, when an \n" 
        + "unknown printer took a galley of type and scrambled it to make a type\n" 
        + " specimen book. It has survived not only five centuries, but also the\n" 
        + " leap into electronic typesetting, remaining essentially unchanged. It\n" 
        + " was popularised in the 1960s with the release of Letraset sheets containing\n" 
        + " Lorem Ipsum passages, and more recently with desktop publishing software \n" 
        + "like Aldus PageMaker including versions of Lorem Ipsum"); 

      SnapshotParameters snapshotParameters = new SnapshotParameters(); 
      snapshotParameters.setFill(Color.TRANSPARENT); 

      Image img = textArea.snapshot(snapshotParameters, null); 
      ImageView imgVw = new ImageView(img); 

      System.out.printf("img.width: %s height: %s%n", img.getWidth(), img.getHeight()); // <= width and height of the image img is 1:1! WHY? 

      Pane pane = new Pane(); 
      pane.getChildren().addAll(imgVw); 

      Scene scene = new Scene(pane, 800,800); 

      pane.setMinWidth(800); 
      pane.setMinHeight(800); 
      pane.setMaxWidth(800); 
      pane.setMaxHeight(800); 

      scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); 
      primaryStage.setScene(scene); 
      primaryStage.show(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 



    public static void main(String[] args) { 
     launch(args); 
    } 
} 

我能想到一個和拍一個快照。但是,對於由javafx.scene.web.WebView顯示的格式化文本,這將失敗。

在此先感謝您的幫助!

回答

1

在快照之前,TextArea需要爲Scene。以下行添加到您的代碼快照調用之前,代碼將作爲你希望:

Scene snapshotScene = new Scene(textArea); 

這要求在snapshot javadoc提到:

注意:爲了讓CSS和佈局功能正常,節點必須是 是場景的一部分(場景可能附加到舞臺,但不需要 )。

+0

非常感謝!完美的答案! – Soir